How can I get an element's serialised HTML with PHP's DOMDocument?

前端 未结 2 1282
無奈伤痛
無奈伤痛 2020-12-18 10:40

This is my example script:

$html = <<
    
Capture this text 1
&l
相关标签:
2条回答
  • 2020-12-18 11:20

    try this

    $dom = new DOMDocument();
    $dom->loadHTML($html);
    
    $xpath = new DOMXPath($dom);
    
    $tags = $xpath->query('//div[@class="main"]');
    
    foreach ($tags as $tag) {
        $innerHTML = '';
    
        $children = $tag->childNodes;
        foreach ($children as $child) {
            $tmp_doc = new DOMDocument();
            $tmp_doc->appendChild($tmp_doc->importNode($child,true));       
            $innerHTML .= $tmp_doc->saveHTML();
        }
    
        var_dump(trim($innerHTML));
    }
    

    -Pascal MARTIN

    0 讨论(0)
  • 2020-12-18 11:21

    Well, nodeValue will give you the node's value. You want what's commonly called outerHTML

    echo $dom->saveXml($tag);
    

    will output what you are looking for in an X(HT)ML compliant way.


    As of PHP 5.3.6 you can also pass a node to saveHtml, which wasnt possible previously:

    echo $dom->saveHtml($tag);
    

    The latter will obey HTML4 syntax. Thanks to Artefacto for that.

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