PHP LIBXML_NOWARNING not suppressing warnings?

2019-02-17 13:33发布

问题:

Using the LIBXML_NOWARNING options flag doesn't stop wanrings when loading html with PHPDOMDocument->loadHTML. Other constants do work though.

In the example below I add the LIBXML_HTML_NODEFDTD to prove that the constants are received(stops a doctype from being added).

$doc=new DOMDocument();
$doc->loadHTML("<tagthatdoesnotexist><h1>Hi</h1></tagthatdoesnotexist>",LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_HTML_NODEFDTD);
echo $doc->saveHTML();

However, warnings are still generated and output. What am I missing?

回答1:

That the LIBXML_NOWARNING option is ignored with DOMDocument::loadHTML() is a flaw in PHP (and to be fixed). It has been recently brought up in a related question "libxml htmlParseDocument ignoring htmlParseOption flags" and filed as PHP Bug #74004 LIBXML_NOWARNING flag ingnored on loadHTML*.

You can, however, manage the error handling your own until the flaw is removed:

  1. Set libxml_use_internal_errors(true) before calling DOMDocument::loadHTML. This will prevent errors from bubbling up to your default error handler. And you can then get at them (if you desire) using other libxml error functions (e.g. libxml_get_errors()).
  2. When using this function, be sure to clear your internal error buffer. If you don't and you are using this in a long running process, you may find that all your memory is used up.
  3. If you want to restore the the default functionality set libxml_use_internal_errors().

Code example:

$doc = new DOMDocument();

# clear errors list if any
libxml_clear_errors();

# use internal errors, don't spill out warnings
$previous = libxml_use_internal_errors(true);

$doc->loadHTML("<tagthatdoesnotexist><h1>Hi</h1></tagthatdoesnotexist>");
echo $doc->saveHTML();

# clear errors list if any
libxml_clear_errors();

# restore previous behavior
libxml_use_internal_errors($previous);

Update

This bug is fixed now.



标签: php libxml2