我正在尝试读取XML提要并将内容存储在服务器上的文件中。执行此操作的脚本在页面加载时通过AJAX调用,并且只有在距离上次更新至少3分钟后才运行。
下面的代码以前似乎工作得很好,但现在我得到了这样的消息:"致命错误:在非对象上调用成员函数asXml()"
承载XML提要的服务器最近被"重置"。我在事件发生的那天就注意到了这个问题,但是,提要仍然可以访问,看起来很好。
if (get_option('last_showtime_check') < (time() - (5 * 60))) {
update_option('last_showtime_check', time());
$url = "http://somedomain.com/showtimes.xml";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
curl_setopt($ch, CURLOPT_URL, $url); // get the url contents
echo var_dump($ch); // Returns "resource (261) of type (curl)"
$data = curl_exec($ch);
curl_close($ch);
$xml = simplexml_load_string($data);
echo var_dump($xml); // Returns "bool(false)"
$xml->asXml('showtimes-test.xml');
}
如果您只是想从远程服务器下载XML文件并将其保存在本地,您可以简单地这样做:
if (get_option('last_showtime_check') < (time() - (5 * 60))) {
file_put_contents('showtimes-test.xml',
file_get_contents('http://somedomain.com/showtimes.xml'));
}
p.s.echo var_dump($xml); // Returns "bool(false)"
-检查你的文件url-它存在吗?
更新
如果设置了正确的Accept
标头,则尝试从中加载XML文件的服务器可能只提供XML文件。很可能是浏览器根据文件ext.尝试第二种方法:
$context = stream_context_create(array(
'http' => array(
'method' => 'GET',
'header' => 'Accept: application/xml'
)
));
file_put_contents('showtimes-test.xml',
file_get_contents('http://somedomain.com/showtimes.xml', false, $context));