Hi,
Is it possible to catch simplexml file errors? I'm connecting to a webservice that sometimes fails, and I need to make the system skip a file if it returns some http error or something similar.
Thanks!
Hi,
Is it possible to catch simplexml file errors? I'm connecting to a webservice that sometimes fails, and I need to make the system skip a file if it returns some http error or something similar.
Thanks!
You're talking about two different things. HTTP errors will have nothing to do with whether an XML file is valid, so you're looking at two separate areas of error handling.
You can take advantage of libxml_use_internal_errors() to suppress any XML parsing errors, and then check for them manually (using libxml_get_errors()) after each parse operation. I'd suggest doing it this way, as your scripts won't produce a ton of E_WARNING
messages, but you'll still find the invalid XML files.
As for HTTP errors, handling those will depend on how you're connecting to the webservice and retrieving the data.
You can set up an error handler within PHP to throw an Exception upon any PHP Errors: (Example and further documentation found here: PHP.net)
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
On error, your simplexml_load_file should return false.
So doing somethign as simple as this:
$xml = @simplexml_load_file('myfile');
if (!$xml) {
echo "Uh oh's, we have an error!";
}
Is one way to detect errors.
If you're not interested in error reporting or logging when the webservice fails you can use the error supression operator:
$xml= @simplexml_load_file('http://tri.ad/test.xml');
if ($xml) {
// Do some stuff . . .
}
But this is a simple hack. A more robust solution would be to load the XML file with cURL, log any failed requests, parse any XML document returned with simplexml_load_string
, log any XML parse errors and then do some stuff with the valid XML.
this is the best script to detect that the xml file has error or not. It hepls me too much. it is small and smart. Thank you very much