I am using DOMDocument class in PHP to remove all the child nodes of ‘body’ element. My code is as follows
$doc=new DOMDocument();
$doc->loadHTMLFile("a.html");
$wrapperDiv=$doc->createElement('div');
$wrapperDiv->setAttribute('class','wrapper');
$body= $doc->getElementsByTagName('body')->item(0);
foreach( $body->childNodes as $child)
{
if($child->nodeName != "#text")
{
$wrapperDiv->appendChild($child);
$body->removeChild($child);
}
}
$body->appendChild($wrapperDiv);
$doc->saveHTMLFile('aaa.html');
at $body->removeChild($child); it gives me error
Uncaught exception ‘DOMException’ with message ‘Not Found Error’ in
C:\xampp\htdocs\test\dum2.php:70 Stack trace: #0
C:\xampp\htdocs\test\dum2.php(70):
DOMNode->removeChild(Object(DOMElement)) #1 {main} thrown in
C:\xampp\htdocs\test\dum2.php on line 70
I have been struggling with this for a long time now but could not figure out what the problem is, as I am new to using this DOMDocument class. The ‘body’ element does contain children!
A node can only have one parent. So I assume that when you called
$wrapperDiv->appendChild($child);,$childis not a child of$bodyanymore and hence$body->removeChild($child);throws an error.Meaning: You don’t need to remove the child as it is already removed.
If on the other hand you really want to remove the children and not append them anywhere else, then remove
$wrapperDiv->appendChild($child);.Update: Indeed it seems that if there are several Element nodes, not all of the nodes are moved: http://codepad.org/8udqSNMj
To fix this, try to iterate over the child elements in reverse order:
http://codepad.org/LtuJN2ZT