Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP DOMDocument error handling

Tags:

In my application I am loading xml from url in order to parse it. But sometimes this url may not be valid. In this case I need to handle errors. I have the following code:

$xdoc = new DOMDocument(); try{   $xdoc->load($url); // This line causes Warning: DOMDocument::load(...)                      // [domdocument.load]: failed to open stream:                       // HTTP request failed! HTTP/1.1 404 Not Found in ... } catch (Exception $e) {   $xdoc = null; }  if($xdoc == null){   // Handle } else {   // Proceed } 

I know I probably doing it wrong, but what's a correct way to handle this kind of exceptions? I don't want to see error messages on my page.

The manual for DOMDocument::load() says:

If an empty string is passed as the filename or an empty file is named, a warning will be generated. This warning is not generated by libxml and cannot be handled using libxml's error handling functions.

But there is no information on how to handle it.

Thanks.

like image 516
Maksim Vi. Avatar asked Nov 18 '09 21:11

Maksim Vi.


1 Answers

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.

like image 139
Øystein Riiser Gundersen Avatar answered Oct 13 '22 05:10

Øystein Riiser Gundersen