5

目前,我正在获取远程站点的 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");

谢谢

4

3 回答 3

4

如果 curl 应该直接写入文件不是很重要,那么您可以在重写本地 feed.xml 之前检查 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);
}

?>
于 2010-02-14T18:27:07.947 回答
3

这个怎么样?如果您只需要检索文档,则无需使用 curl。

$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');
}
于 2010-02-14T19:11:47.263 回答
0

在我整理的一个类中,我有一个函数可以检查远程文件是否存在以及它是否及时响应:

/**
* 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

于 2012-04-26T23:43:15.120 回答