views:

733

answers:

5

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!

+2  A: 

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.

zombat
+2  A: 

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");
Dominic Barnes
I don't want to abort the system in case of error, just skip the function and continue the normal proccess
yoda
Well, by definition Exceptions do not abort execution. If you wrap your simplexml_load_file() within a try-catch block, you can intercept any error.
Dominic Barnes
+1  A: 

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.

Andy Baird
almost, but you forgot to suppress the error on simplexml, like @pygorex1's example. Still, +1
yoda
Thanks, good call - I edited this
Andy Baird
A: 

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.

pygorex1
A: 

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

Ravi