Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP LIBXML_NOWARNING not suppressing warnings?

Tags:

php

libxml2

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?

like image 952
user2782001 Avatar asked Jan 25 '17 06:01

user2782001


1 Answers

The LIBXML_NOWARNING option is ignored with DOMDocument::loadHTML() is a bug 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 bug is fixed:

  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. Make sure you clear the internal error buffer while using the mentioned function. 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.

like image 84
Prashant Pokhriyal Avatar answered Oct 21 '22 00:10

Prashant Pokhriyal