2012-08-05 93 views
0

我正在读取一个数字的XML文件。然后,它使用该数字作为可用作XML的URL参数。有一些XML不存在的情况。当发生这种情况时,我希望页面可以报告没有该游戏的统计数据。检查xml是否存在(simplexml_load_file)

TL; DR:如果XML不存在,我怎么才能让它简单地回显“No Stats”。

$gamepage = simplexml_load_file('' . rawurlencode($gamelink) . '?xml=1'); 
+0

XML是一个本地文件,还是你通过http拉?如果是本地的,只是['file_exists()'](http://us3.php.net/manual/en/function.file-exists.php) – 2012-08-05 22:13:35

+0

它不是本地的 – user1568736 2012-08-05 22:14:28

+0

请参阅http://stackoverflow.com/questions/1722613/check-if-a-remote-page-exists-using-php and [many other examples](http://stackoverflow.com/search?q=%5Bphp%5D+remote+file+exists)。 – 2012-08-05 22:17:08

回答

5
$a = simplexml_load_string($somestring); 
if($a===FALSE) { 
    echo 'No Stats'; 
} else { 
    echo "Valid XML found... processing."; 
} 

简单得很。

+0

如果返回的xml是空白,这仍然会引发错误。这是一个更好的解决方案:http://stackoverflow.com/a/11633904/1312282 – hobailey 2014-05-15 13:22:12