如果 XML 加载文件超时或无法加载,是否可以绕过该文件?



我正在读取一个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:wampwwwclairvoyantextrasget-readers.php on line 10
Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in C:wampwwwclairvoyantextrasget-readers.php on line 11
Exception: String could not be parsed as XML in C:wampwwwclairvoyantextrasget-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);

我错过了什么吗?我是否需要调整网站其他地方的参考点?

嗯,我想我已经想出了一个很好的方法。

我正在沿着正确的轨道前进,我确实需要在包含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 &amp; conditions</a></span>
</div>
"; } else { $xml = new SimpleXmlElement($url); } // If XML can't be loaded, show error message

然后在我包含get-readers.php的每个地方,在包含之后是一个foreach,从XML内容中获取数组。

我将其放入基于if($xml)IF语句中。在这一行的正上方,我回显$xmlMsg以显示如果设置了错误消息。(如果XML文件加载,消息设置为'';)

希望这对某人有所帮助!

相关内容

  • 没有找到相关文章

最新更新