目前,我抓住一个远程站点的XML饲料和我的服务器上保存本地副本在PHP解析。

但问题是我怎么去增加一些检查,在PHP中,看是否feed.xml文件是有效的,如果是使用feed.xml。

和如果无效有错误(其有时远程XML饲料萨姆显示空白feed.xml),从先前的抓斗服务feed.xml的备份有效副本/保存?

代码敛feed.xml

<?php
/**
* Initialize the cURL session
*/
$ch = curl_init();
/**
* Set the URL of the page or file to download.
*/
curl_setopt($ch, CURLOPT_URL,
'http://domain.com/feed.xml');
/**
* Create a new file
*/
$fp = fopen('feed.xml', 'w');
/**
* Ask cURL to write the contents to a file
*/
curl_setopt($ch, CURLOPT_FILE, $fp);
/**
* Execute the cURL session
*/
curl_exec ($ch);
/**
* Close cURL session and file
*/
curl_close ($ch);
fclose($fp);
?>

到目前为止只有这加载它

$xml = @simplexml_load_file('feed.xml') or die("feed not loading");

感谢

有帮助吗?

解决方案

如果它不pricipial那卷曲应该直接写入文件,然后你可以检查XML重写本地feed.xml前:

<?php
/**
* Initialize the cURL session
*/
$ch = curl_init();
/**
* Set the URL of the page or file to download.
*/
curl_setopt($ch, CURLOPT_URL, 'http://domain.com/feed.xml');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$xml = curl_exec ($ch);
curl_close ($ch);
if (@simplexml_load_string($xml)) {
    /**
    * Create a new file
    */
    $fp = fopen('feed.xml', 'w');
    fwrite($fp, $xml);
    fclose($fp);
}

?>

其他提示

这个怎么样?无需使用卷曲,如果你只需要检索文档。

$feed = simplexml_load_file('http://domain.com/feed.xml');

if ($feed)
{
    // $feed is valid, save it
    $feed->asXML('feed.xml');
}
elseif (file_exists('feed.xml'))
{
    // $feed is not valid, grab the last backup
    $feed = simplexml_load_file('feed.xml');
}
else
{
    die('No available feed');
}

在I类放在一起,我有检查,如果远程文件存在的函数,并且,如果它的响应及时:

/**
* Check to see if remote feed exists and responding in a timely manner
*/
private function remote_file_exists($url) {
  $ret = false;
  $ch = curl_init($url);

  curl_setopt($ch, CURLOPT_NOBODY, true); // check the connection; return no content
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1); // timeout after 1 second
  curl_setopt($ch, CURLOPT_TIMEOUT, 2); // The maximum number of seconds to allow cURL functions to execute.
  curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.0; da; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11');

  // do request
  $result = curl_exec($ch);

  // if request is successful
  if ($result === true) {
    $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($statusCode === 200) {
      $ret = true;
    }
  }
  curl_close($ch);

  return $ret;
}

在全类包含的回落代码,以确保我们总是有一些帮助。

博客文章,解释了满级是在这里:的http:// weedygarden.net/2012/04/simple-feed-caching-with-php/

代码是在这里: https://github.com/erunyon/FeedCache

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top