82

I need to parse some HTML files, however, they are not well-formed and PHP prints out warnings to. I want to avoid such debugging/warning behavior programatically. Please advise. Thank you!

Code:

// create a DOM document and load the HTML data
$xmlDoc = new DomDocument;
// this dumps out the warnings
$xmlDoc->loadHTML($fetchResult);

This:

@$xmlDoc->loadHTML($fetchResult)

can suppress the warnings but how can I capture those warnings programatically?

thomasrutter
  • 104,920
  • 24
  • 137
  • 160
Viet
  • 16,604
  • 31
  • 94
  • 134
  • Try this solution - seems to be much easier - http://stackoverflow.com/questions/6090667/php-domdocument-errors-warnings-on-html5-tags – Marcin Dec 28 '12 at 19:35
  • Converting lousy input to proper output is what pays the bills ;) The [recover option is in the manual](http://nl1.php.net/manual/en/class.domdocument.php#domdocument.props.recover). it's just a boolean. You can just call `$dom->saveHTML()` so see what kind if document libxml is trying to make of your `$html` input, usually it's pretty close/ok. – Wrikken Jul 09 '13 at 22:57

4 Answers4

229

Call

libxml_use_internal_errors(true);

prior to processing with with $xmlDoc->loadHTML()

This tells libxml2 not to send errors and warnings through to PHP. Then, to check for errors and handle them yourself, you can consult libxml_get_last_error() and/or libxml_get_errors() when you're ready.

thomasrutter
  • 104,920
  • 24
  • 137
  • 160
96

To hide the warnings, you have to give special instructions to libxml which is used internally to perform the parsing:

libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_clear_errors();

The libxml_use_internal_errors(true) indicates that you're going to handle the errors and warnings yourself and you don't want them to mess up the output of your script.

This is not the same as the @ operator. The warnings get collected behind the scenes and afterwards you can retrieve them by using libxml_get_errors() in case you wish to perform logging or return the list of issues to the caller.

Whether or not you're using the collected warnings you should always clear the queue by calling libxml_clear_errors().

Preserving the state

If you have other code that uses libxml it may be worthwhile to make sure your code doesn't alter the global state of the error handling; for this, you can use the return value of libxml_use_internal_errors() to save the previous state.

// modify state
$libxml_previous_state = libxml_use_internal_errors(true);
// parse
$dom->loadHTML($html);
// handle errors
libxml_clear_errors();
// restore
libxml_use_internal_errors($libxml_previous_state);
Ja͢ck
  • 161,074
  • 33
  • 239
  • 294
  • 2
    @Greeso: It is set to the *previous* value. That's done by the concept that it might have been configured for some other code globally different to `FALSE` and setting it to `FALSE` afterwards would destroy that setting. By using the previous return value `$libxml_previous_state` those potential side-effects are prevented because the original configuration has been restored independent to this place needs. The `libxml_use_internal_errors()` setting is global, so it's worth to take some care. – hakre Jul 10 '13 at 08:31
  • If there are already libxml errors pending, won't this eat them? – cHao Aug 18 '16 at 04:03
  • @cHao isn't it reasonable to assume that you're starting off with a blank slate? :) – Ja͢ck Aug 18 '16 at 04:05
  • @Ja͢ck: Nope. If something previously called `libxml_use_internal_errors(true)`, then it may be waiting to handle whatever errors have arisen. – cHao Aug 18 '16 at 04:13
29

Setting the options "LIBXML_NOWARNING" & "LIBXML_NOERROR" works perfectly fine too:

$dom->loadHTML($html, LIBXML_NOWARNING | LIBXML_NOERROR);
Joshua Ott
  • 745
  • 7
  • 12
14

You can install a temporary error handler with set_error_handler

class ErrorTrap {
  protected $callback;
  protected $errors = array();
  function __construct($callback) {
    $this->callback = $callback;
  }
  function call() {
    $result = null;
    set_error_handler(array($this, 'onError'));
    try {
      $result = call_user_func_array($this->callback, func_get_args());
    } catch (Exception $ex) {
      restore_error_handler();        
      throw $ex;
    }
    restore_error_handler();
    return $result;
  }
  function onError($errno, $errstr, $errfile, $errline) {
    $this->errors[] = array($errno, $errstr, $errfile, $errline);
  }
  function ok() {
    return count($this->errors) === 0;
  }
  function errors() {
    return $this->errors;
  }
}

Usage:

// create a DOM document and load the HTML data
$xmlDoc = new DomDocument();
$caller = new ErrorTrap(array($xmlDoc, 'loadHTML'));
// this doesn't dump out any warnings
$caller->call($fetchResult);
if (!$caller->ok()) {
  var_dump($caller->errors());
}
troelskn
  • 107,146
  • 23
  • 127
  • 148
  • 10
    Seems like a lot of overkill for the situation. Note PHP's libxml2 functions. – thomasrutter May 17 '10 at 07:01
  • Good point, Thomas. I didn't know about these functions when I wrote this answer. If I'm not mistaken, it does the same thing internally btw. – troelskn May 17 '10 at 08:27
  • 1
    It has the same effect in this case yes, though it's done at a different level: with the above solution, PHP errors are generated but suppressed but with mine, they don't become PHP errors. I personally feel that if doing something involves suppressing PHP errors either through @ or set_error_handler(), then it's the wrong way to do it. That's just my opinion though. Note that PHP errors and exceptions are a different thing entirely - using try {} catch() {} is fine. – thomasrutter May 18 '10 at 07:44
  • 2
    I think I've seen some bug reports, that suggests that `libxml_use_internal_errors` hooks in to php's error handler. – troelskn May 18 '10 at 08:48
  • I hope people scroll past this answer down to the better answers below. – thomasrutter Dec 18 '20 at 00:46