PHP DOMDocument error handling

前端 未结 5 1644
予麋鹿
予麋鹿 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:30

    To disable throwing errors:

    $internal_errors = libxml_use_internal_errors(true);
    
    $dom = new DOMDocument();
    // etc...
    
    libxml_use_internal_errors($internal_errors);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-03 05:44
    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.

    0 讨论(0)
  • 2020-12-03 05:50

    From php.net

    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.

    In your production environment you shouldn't have errors displayed to the user. They don't need to see them so taking this into account you can use...

    $xdoc = new DOMDocument();
    if ( $xdoc->load($url) ) {
        // valid
    }
    else {
        // invalid
    }
    
    0 讨论(0)
  • 2020-12-03 05:54

    For me , following did the trick

    $feed = new DOMDocument();  
    $res= @$feed->load('http://www.astrology.com/horoscopes/daily-extended.rss');
    if($res==1){
               //do sth
              }
    
    0 讨论(0)
提交回复
热议问题