Avoid DOMDocument XML warnings in php

前端 未结 3 2035
悲&欢浪女
悲&欢浪女 2020-12-10 04:57

I\'m fetching xml files from a server and sometimes I\'m getting a non-valid xml files, because of this I\'m getting a warning:

Warning: DOMDocument::load()          


        
相关标签:
3条回答
  • 2020-12-10 05:14

    Use set_error_handler.

    set_error_handler("yourHandler", E_WARNING);
    
    0 讨论(0)
  • 2020-12-10 05:18

    You have two choices. Either use the @ error control operator in your load() call, e.g. @$dom->load(), which is somewhat slow because it globally changes the value of display_errors to off, executes the function and sets it back to on.

    The other option, which I personally prefer (I hate the @ operator, I can't stand to see it in my code) is to save the old value of libxml_use_internal_errors, enable it using libxml_use_internal_errors(TRUE), call the function, clear the errors buffer and restore the old value. Here's a snippet from my code that does that:

    <?php
    $previous_value = libxml_use_internal_errors(TRUE);
    $doc->loadHTML((string)$e->response->getBody());
    libxml_clear_errors();
    libxml_use_internal_errors($previous_value);
    

    I can't comment on answers yet, so I'll write it here:

    • Michael solution makes it less strict, but it'll still issue warnings for some of the errors:
    nadav@shesek:~$ php -r '$dom=new DOMDocument; $dom->strictErrorChecking = FALSE ; $dom->loadHTML("<xy></zx>");'
    PHP Warning:  DOMDocument::loadHTML(): Tag xy invalid in Entity, line: 1 in Command line code on line 1
    
    • DON'T do what Fran Verona suggested - globally disabling error reporting is something you should never do. In production, set your own error handler and display a prettier message to the user, and make sure the error is logged somewhere - but never disable it completely. Setting error_reporting to 0 will cause PHP to disable error logging too.
    • Xeon06 solution is problematic because you're effecting the entire script error handler for a specific piece of code. Using your own error handler that simply ignores the error causes the same issues as Fran's solution.
    0 讨论(0)
  • 2020-12-10 05:31

    Turn off strict error checking:

    $dom = new DOMDocument();
    $dom->strictErrorChecking = FALSE ;
    
    $dom->load('/path/to/file.xml');
    if (!$dom->validate()) {
       // Invalid XML!
    }
    
    0 讨论(0)
提交回复
热议问题