Reputation: 475
I am looking to handle a situation whereby the XML file that I at trying to retrieve is not ready or is not available.
I am using:
$object = simplexml_load_string($file);
Sometimes, I get the following error:
'Start tag expected, '<' not found in etc...'
I have tried the following, and it doesn't work.
if($object === false){
// code here
}
Upvotes: 0
Views: 6309
Reputation: 26755
simplexml_load_string can return false if there is an error. It can also emit a warning.
From the manual:
Returns an object of class SimpleXMLElement with properties containing the data held within the xml document, or FALSE on failure.
Produces an E_WARNING error message for each error found in the XML data.
Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.
// suppress warnings so we can handle them ourselves
libxml_use_internal_errors(true);
$object = simplexml_load_string($file);
if ($object === false) {
// oh no
$errors = libxml_get_errors();
// do something with them
print_r($errors);
// really you'll want to loop over them and handle them as necessary for your needs
}
More detail on libxml_get_errors
here.
Upvotes: 1