DOMDocument::loadHTML error

前端 未结 4 1390
囚心锁ツ
囚心锁ツ 2020-12-02 11:52

I build a script that combines all css on a page together to use it in my cms. It worked fine for a long time now i i get this error:


相关标签:
4条回答
  • 2020-12-02 12:38

    HTML5 elements are still not supported, but you can silence libxml errors completely with the $options parameter.

    Just set

    $doc = new DOMDocument();
    $doc->loadHTMLFile("html5.html", LIBXML_NOERROR);
    

    This option is preferred over @ which silences PHP errors.

    But be careful, libxml is very forgiving and it will parse a broken HTML document. If you silence libxml errors you might not even be aware that the HTML is malformed.

    0 讨论(0)
  • 2020-12-02 12:42

    With a DOMDocument object, you should be able to place an @ before the load method in order to SUPPRESS all WARNINGS.

    $dom = new DOMDocument;
    @$dom->loadHTML($source);
    

    And carry on.

    0 讨论(0)
  • 2020-12-02 12:42

    Most people do not realize the difference between HTML and XML as languages and HTML and XML in regards to parsers. A parser takes code and the HTML and XML parsers are completely different. While there are some minor things XML parsers will tolerate in browsers (e.g. duplicate id values) they don't mess around with junk that looks like code.

    PHP's XML parser is even stricter and doesn't allow duplicate id values. Additionally since anything can be an element (e.g. footer, header, section) PHP's XML parser will not complain about unknown HTML5+ elements.

    $dom->loadXML($xml);
    

    For anyone developing on client side I highly recommend using the XML parser to handle your HTML5 code and since I started developing in the 2000s in to 2020 Gecko browsers (e.g. Waterfox, Firefox) have the best XML parser as the entire page will break and you'll get an explicit error message. Stricter code yields better results if you can comprehend quality eventually yields quantity though the opposite is not true.

    0 讨论(0)
  • 2020-12-02 12:52

    Header, Nav and Section are elements from HTML5. Because HTML5 developers felt it is too difficult to remember Public and System Identifiers, the DocType declaration is just:

    <!DOCTYPE html>
    

    In other words, there is no DTD to check, which will make DOM use the HTML4 Transitional DTD and that doesnt contain those elements, hence the Warnings.

    To surpress the Warnings, put

    libxml_use_internal_errors(true);
    

    before the call to loadHTML and

    libxml_use_internal_errors(false);
    

    after it.

    An alternative would be to use https://github.com/html5lib/html5lib-php.

    0 讨论(0)
提交回复
热议问题