抓取、缓存和解析远程 XML 源,在 PHP 中进行验证检查。

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");

谢谢

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);
}

?>

嗨,我再次回顾这段代码,似乎无法将远程XML文件拉取并保存到本地,而我在第一篇帖子中发布的代码可以工作,但保存的XML文件被截断了?有什么想法吗? - p4guru

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');
}

谢谢Josh,我一定会好好学习的。很高兴在这个网站上注册 :) - p4guru

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接