PHP DOMDocument error handling
From what I can gather from the documentation, handling warnings issued by this method is tricky because they are not generated by the libxml extension and thus cannot be handled by libxml_get_last_error()
. You could either use the error suppression operator and check the return value for false
...
if (@$xdoc->load($url) === false) // ...handle it
...or register an error handler which throws an exception on error:
function exception_error_handler($errno, $errstr, $errfile, $errline ) { throw new ErrorException($errstr, 0, $errno, $errfile, $errline);}
and then catch it.
set_error_handler(function($number, $error){ if (preg_match('/^DOMDocument::loadXML\(\): (.+)$/', $error, $m) === 1) { throw new Exception($m[1]); }});$xml = new DOMDocument();$xml->loadXML($xmlData);restore_error_handler();
That works for me in PHP 5.3. But if you're not using loadXML
, you might need to do some modifications.
To disable throwing errors:
$internal_errors = libxml_use_internal_errors(true);$dom = new DOMDocument();// etc...libxml_use_internal_errors($internal_errors);