如果XML文件为空,则捕获PHP错误 [英] Catching PHP errors if XML file is empty
本文介绍了如果XML文件为空,则捕获PHP错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我从一个XML文件中获取一些信息,如下所示:
so I'm grabbing some information from an XML file like so:
$url = "http://myurl.blah";
$xml = simplexml_load_file($url);
除了有时XML文件为空,我需要代码正常失败,但我似乎不能弄清楚如何抓住PHP错误。我试过这个:
Except sometimes the XML file is empty and I need the code to fail gracefully but I can't seem to figure out how to catch the PHP error. I tried this:
if(isset(simplexml_load_file($url)));
{
$xml = simplexml_load_file($url);
/*rest of code using $xml*/
}
else {
echo "No info avilable.";
}
但它不工作。我想你不能这样使用ISSET。任何人都知道如何抓住错误?
But it doesn't work. I guess you can't use ISSET that way. Anyone know how to catch the error?
推荐答案
$xml = file_get_contents("http://myurl.blah");
if (trim($xml) == '') {
die('No content');
}
$xml = simplexml_load_string($xml);
或者可能稍微提高效率,但不一定推荐,因为它会使错误无效:
Or, possibly slightly more efficient, but not necessarily recommended because it silences errors:
$xml = @simplexml_load_file($url);
if (!$xml) {
die('error');
}
这篇关于如果XML文件为空,则捕获PHP错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文