Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove all child elements of body element with DOMDocument?

I'm trying to remove all body children with 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 am doing wrong... please tell me.

like image 689
alex Avatar asked Feb 10 '11 01:02

alex


1 Answers

Well, the problem is that you're updating the $bodyChildren iterator (it's not an array, it's a DomNodeList object) as you're looping over it. Instead, try doing this:

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

It seems a bit backwards, but it should work for your needs...

like image 110
ircmaxell Avatar answered Oct 13 '22 21:10

ircmaxell