13

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() [domdocument.load]: Start tag expected, '<' not found in 

How can I catch this warning and delete the file?

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
Mokus
  • 10,174
  • 18
  • 80
  • 122
  • possible duplicate of [try and catch a warning](http://stackoverflow.com/questions/1241728/try-and-catch-a-warning) (For the more broad answer) – Brad Christie Aug 16 '11 at 17:32

3 Answers3

43

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.
shesek
  • 4,584
  • 1
  • 28
  • 27
3

Use set_error_handler.

set_error_handler("yourHandler", E_WARNING);
Benjamin Dubois
  • 971
  • 7
  • 11
Alex Turpin
  • 46,743
  • 23
  • 113
  • 145
2

Turn off strict error checking:

$dom = new DOMDocument();
$dom->strictErrorChecking = FALSE ;

$dom->load('/path/to/file.xml');
if (!$dom->validate()) {
   // Invalid XML!
}
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390