Reputation: 48453
I have in database several XML feeds which I regularly checking. How I do process data:
I load these XML links from DB and in loop through the simplexml_load_file()
I am parsing data.
But sometimes the script is terminated because of error caused by wrong format of XML file, for example:
Warning: simplexml_load_file() [function.simplexml-load-file]: URL_ADDRESS:1: parser error : Invalid XML encoding name in path_to_script on line 98
Warning: simplexml_load_file() [function.simplexml-load-file]: <?xml version="1.0" encoding=""?> in path_to_scriptp on line 98
Warning: simplexml_load_file() [function.simplexml-load-file]: ^ in path_to_script on line 98
Warning: Invalid argument supplied for foreach() in path_to_script on line 99
Is there any way to handle this error and when an error is occurred, then would be this XML feed skipped and the script would continue with the next one?
Upvotes: 0
Views: 2483
Reputation: 197757
If simplexml_load_file
Docs fails to load the file, it will return false
. If you use the LIBXML_NOERROR
optionDocs, the error(s) won't be reported either.
So all you need to do is to check the return value:
foreach ($files as $file)
{
$xml = simplexml_load_file($file, null, LIBXML_NOERROR);
if ($xml === false) {
continue;
}
... process $xml ...
}
Online demo: http://codepad.viper-7.com/EXG7VP
Upvotes: 1
Reputation: 10908
Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.
Upvotes: 1