Remove parent element, keep all inner children in DOMDocument with saveHTML

前端 未结 5 2172
情歌与酒
情歌与酒 2021-01-04 20:42

I\'m manipulating a short HTML snippet with XPath; when I output the changed snippet back with $doc->saveHTML(), DOCTYPE gets added, and HTML / BODY

5条回答
  •  感动是毒
    2021-01-04 20:59

    Here how I've done it:

    -- Quick helper function that gives you HTML contents for specific DOM element

    function nodeContent($n, $outer=false) {
       $d = new DOMDocument('1.0');
       $b = $d->importNode($n->cloneNode(true),true);
       $d->appendChild($b); $h = $d->saveHTML();
       // remove outter tags
       if (!$outer) $h = substr($h,strpos($h,'>')+1,-(strlen($n->nodeName)+4));
       return $h;
    }
    

    -- Find body node in your doc and get its contents

    $query = $xpath->query("//body")->item(0);
    if($query)
    {
        echo nodeContent($query);
    }
    

    UPDATE 1:

    Some extra info: Since PHP/5.3.6, DOMDocument->saveHTML() accepts an optional DOMNode parameter similarly to DOMDocument->saveXML(). You can do

    $xpath = new DOMXPath($doc);
    $query = $xpath->query("//body")->item(0);
    echo $doc->saveHTML($query);
    

    for others, the helper function will help

提交回复
热议问题