目前,我正在抓取远程站点的XML feed并在我的服务器上保存本地副本以便在PHP中进行解析.
问题是如何在PHP中添加一些检查以查看feed.xml文件是否有效,如果是,请使用feed.xml.
如果错误无效(有时远程XML提供某些显示空白feed.xml),请从之前的抓取/保存中提供feed.xml的备份有效副本?
代码抓取feed.xml
/**
* 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");
谢谢
最佳答案:
如果curl不应该直接写入文件,那么你可以在重写本地feed.xml之前检查XML:
/**
* 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);
}
?>
标签:php,curl,xml,xml-validation
来源: https://codeday.me/bug/20190515/1111415.html