我正在阅读XML文件并使用new simplexmlelement
加载它。
有时,因为XML文件位于远程服务器上,所以加载可能需要很长时间,如果远程服务器关闭,有时根本无法加载。
最初我是这样加载XML的:
$url = file_get_contents('PATH_TO_XML');
$xml = new SimpleXmlElement($url);
所以我想提出一种方法,如果XML文件花了太长时间来响应,或者根本无法加载,PHP就会绕过它,加载网站的其余部分,并产生一个简单的错误消息,无论站点上引用XML文件的哪个位置。
所以我在线阅读,并将其添加到代码中:
$context = stream_context_create(array(
'http' => array(
'method' => 'GET',
'timeout' => 10,
)
));
$url = file_get_contents(PATH_TO_XML', false, $context);
$xml = new SimpleXmlElement($url);
但我的问题是,即使这样,我在WAMP环境中运行时也会收到以下错误:
Warning: file_get_contents(http://www.inveroak.co.uk/readerimages/livepanel/91221.xml): failed to open stream: HTTP request failed! HTTP/1.1 503 Service Unavailable in C:\wamp\www\clairvoyant\extras\get-readers.php on line 10
Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in C:\wamp\www\clairvoyant\extras\get-readers.php on line 11
Exception: String could not be parsed as XML in C:\wamp\www\clairvoyant\extras\get-readers.php on line 11
get-readers.php#10:
$url = file_get_contents('http://www.inveroak.co.uk/readerimages/livepanel/91221.xml', false, $context);
get-readers.php#11:
$xml = new SimpleXmlElement($url);
有什么我想念的吗?我是否需要在网站的其他地方调整参考点?
答案 0 :(得分:0)
我正沿着正确的轨道前进,我确实需要为包含get-readers.php文件的网站的每个部分添加一个条件。
所以我所做的就是把它添加到get-readers.php:
// create the context
$arContext['http']['timeout'] = 0;
$context = stream_context_create($arContext);
// fetch XML
$url = @file_get_contents('http://www.inveroak.co.uk/readerimages/livepanel/91221.xml', false, $context);
$xmlMsg = '';
if($url === false) { $xmlMsg = "
<div class='xmlError'>
<span class='title'>Oh no, something's gone wrong!</span>
<span>We're having trouble showing our available readers at the moment. This is usually only a temporary issue though, and we promise we are working on it!</span><br>
<span>You can still book a reading by phoning one of our trained operators!</span>
<div class='action'><div class='inside silver'><span>Pay by card</span>Call <span class='number'>".variable('local_no')."</span> and pay over the phone using a credit or debit card</div></div>
<div class='action'><div class='inside green'><span>Pay by phone</span>Call <span class='number'>".variable('prem_no')."</span> and pay using your phone bill. It's quick and easy!</div></div>
<span class='small'>0906 calls cost £1.53/min + network extras. <a href='/terms-conditions'>Full terms & conditions</a></span>
</div>
"; } else { $xml = new SimpleXmlElement($url); } // If XML can't be loaded, show error message
然后在每个地方我都包括了get-readers.php,就在include之后是一个从XML内容中获取数组的foreach。
我将其添加到基于IF
的{{1}}语句中。在该行的正上方,我回显if($xml)
以显示错误消息(如果已设置)。 (如果加载XML文件,则消息设置为$xmlMsg
)
希望能帮助别人!