Catching PHP errors if XML file is empty

2019-02-19 20:09发布

问题:

so I'm grabbing some information from an XML file like so:

$url = "http://myurl.blah";
$xml = simplexml_load_file($url);

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.";
}

But it doesn't work. I guess you can't use ISSET that way. Anyone know how to catch the error?

回答1:

$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');
}


回答2:

Don't use isset here.

// 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.";
}


回答3:

if (($xml = simplexml_load_file($url)) !== false) {
  // Everything is OK. Use $xml object.
} else {
  // Something has gone wrong!
}


回答4:

From PHP manual, error handling (click here):

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();
}