所以我从一个XML文件中获取一些信息,比如:
$url = "http://myurl.blah";
$xml = simplexml_load_file($url);
除了有时XML文件是空的,我需要代码正常地失败,但我似乎不知道如何捕捉PHP错误。我试过这个:
if(isset(simplexml_load_file($url)));
{
$xml = simplexml_load_file($url);
/*rest of code using $xml*/
}
else {
echo "No info avilable.";
}
但它不起作用。我想你不能那样使用ISSET。有人知道如何捕捉错误吗?
$xml = file_get_contents("http://myurl.blah");
if (trim($xml) == '') {
die('No content');
}
$xml = simplexml_load_string($xml);
或者,可能效率稍高,但不一定推荐,因为它可以消除错误:
$xml = @simplexml_load_file($url);
if (!$xml) {
die('error');
}
此处不要使用isset
。
// Shutdown errors (I know it's bad)
$xml = @simplexml_load_file($url);
// Check you have fetch a response
if (false !== $xml); {
//rest of code using $xml
} else {
echo "No info avilable.";
}
if (($xml = simplexml_load_file($url)) !== false) {
// Everything is OK. Use $xml object.
} else {
// Something has gone wrong!
}
从PHP手册,错误处理(单击此处):
var_dump(libxml_use_internal_errors(true));
// load the document
$doc = new DOMDocument;
if (!$doc->load('file.xml')) {
foreach (libxml_get_errors() as $error) {
// handle errors here
}
libxml_clear_errors();
}