我在PHP中使用DOMDocument
类来删除'body'元素的所有子节点。我的代码如下
$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');
在$body->removeChild($child);
它给了我错误
未捕获的异常'DOMException',中包含消息'Not Found Error' C:\ xampp \ htdocs \ test \ dum2.php:70堆栈跟踪:#0 C:\ XAMPP \ htdocs中\测试\ dum2.php(70): DOMNode-> removeChild(Object(DOMElement))#1 {main}抛出 第70行的C:\ xampp \ htdocs \ test \ dum2.php
我一直在努力解决这个问题很长一段时间但是无法弄清问题是什么,因为我不熟悉使用这个DOMDocument
类。 'body'元素确实包含了孩子!
答案 0 :(得分:3)
节点只能有一个父节点。因此,我假设当您致电$wrapperDiv->appendChild($child);
时,$child
不再是$body
的孩子,因此$body->removeChild($child);
会引发错误。
含义:您不需要删除已删除的子项。
另一方面,如果你真的想删除孩子而不将其附加到其他地方,请删除$wrapperDiv->appendChild($child);
。
更新:确实,如果有多个Element节点,并非所有节点都被移动:http://codepad.org/8udqSNMj
要解决此问题,请尝试以相反的顺序迭代子元素:
$children = $body->childNodes;
for($i = $children->length; $i--;) {
$child = $children->item($i);
if($child->nodeName != "#text") {
$wrapperDiv->appendChild($child);
}
}