PHP LIBXML_NOWARNING not suppressing warnings?

浪尽此生 提交于 2020-01-29 13:23:28

问题


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.



来源:https://stackoverflow.com/questions/41844778/php-libxml-nowarning-not-suppressing-warnings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!