PHP DOMDocument error handling

前端 未结 5 1675
予麋鹿
予麋鹿 2020-12-03 05:01

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:

5条回答
  •  天涯浪人
    2020-12-03 05:38

    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.

提交回复
热议问题