Friday 9 December 2016

Avoid DOMDocument XML warnings in php

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:




$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("");'
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.

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...