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

前端 未结 5 2127
情歌与酒
情歌与酒 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 21:08

    saveHTML can output a subset of document, meaning we can ask it to output every child node one by one, by traversing body.

    $doc = new DOMDocument();
    $doc->loadHTML('

    Title...

    ...to be one of those crowning achievements...

    '); // manipulation goes here // Let's traverse the body and output every child node $bodyNode = $doc->getElementsByTagName('body')->item(0); foreach ($bodyNode->childNodes as $childNode) { echo $doc->saveHTML($childNode); }

    This might not be a most elegant solution, but it works. Alternatively, we can wrap all children nodes inside some container element (say a div) and output only that container (but container tag will be included in the output).

提交回复
热议问题