0

I am using php's DomDocument class to load an HTML file and then empty its contents. The problem is when I do .removeChild() it gives me 'Not Found Error'. heres my code

$doc=new DOMDocument();
$doc->loadHTMLFile("a.html");
$body= $doc->getElementsByTagName('body')->item(0);
foreach($body->childNodes as $child)
{
        $body->removeChild($child);

} 

$child is of DOMText type....may be because removeChild expects DOMNode and not DOMText? if yes then how can i iterate over childNodes such that $child is of type DOMNode?

samach
  • 3,244
  • 10
  • 42
  • 54

1 Answers1

0

Use a for loop instead of a foreach loop.

$doc=new DOMDocument();
$doc->loadHTML("c.html");
$doc->preserveWhiteSpace = true;
$body = $doc->getElementsByTagName('body')->item(0);
$children = $body->childNodes;
$length = $children->length;
for($i = 0 ; $i < $length; $i++) {
    $child = $children->item($i);
    if ($child)
        $body->removeChild($child);
}
$html = $doc->saveHTML();
echo $html;
Darth Egregious
  • 18,184
  • 3
  • 32
  • 54