How to close unclosed HTML Tags?

后端 未结 8 594
名媛妹妹
名媛妹妹 2020-11-30 01:56

Whenever we are fetching some user inputed content with some editing from the database or similar sources, we might retrieve the portion which only contains the opening tag

8条回答
  •  清歌不尽
    2020-11-30 02:18

    For HTML fragments, and working from KJS's answer I have had success with the following when the fragment has one root element:

    $dom = new DOMDocument();
    $dom->loadHTML($string);
    $body = $dom->documentElement->firstChild->firstChild;
    $string = $dom->saveHTML($body);
    

    Without a root element this is possible (but seems to wrap only the first text child node in p tags in text

    para

    text):

    $dom = new DOMDocument();
    $dom->loadHTML($string);
    $bodyChildNodes = $dom->documentElement->firstChild->childNodes;
    
    $string = '';
    foreach ($bodyChildNodes as $node){
       $string .= $dom->saveHTML($node);
    }
    

    Or better yet, from PHP >= 5.4 and libxml >= 2.7.8 (2.7.7 for LIBXML_HTML_NOIMPLIED):

    $dom = new DOMDocument();
    
    // Load with no html/body tags and do not add a default dtd
    $dom->loadHTML($string, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    
    $string = $dom->saveHTML();    
    

提交回复
热议问题