How to remove all child elements of a body element using a DOMDocument?

I am trying to remove all bodychildren with a DOMDocument.

$dom = new DomDocument();

$dom->loadHTML($buffer);
$dom->preserveWhiteSpace = FALSE; 

$body = $dom->getElementsByTagName('body')->item(0);

$bodyChilden = $body->childNodes; // NULL, so invalid argument for foreach

foreach($bodyChildren as $child) {
    $child->parentNode->removeChild($child);
}

echo $dom->saveHTML();

I'm not sure what I'm doing wrong ... please tell me.

+5
source share
1 answer

Well, the problem is that you are updating the iterator $bodyChildren(this is not an array, this is an object DomNodeList) when you iterate over it. Instead, try doing this:

while ($bodyChildren->length > 0) {
    $body->removeChild($bodyChildren->item(0));
}

It seems a little back, but it should work for your needs ...

+7
source

All Articles