![](/img/trans.png)
[英]PHP appendChild giving nice fatal error -Uncaught exception 'DOMException' with message 'Hierarchy Request Error - how can I add html AFTER a tag
[英]Uncaught exception 'DOMException' with message 'Hierarchy Request Error'
在将节点替换或添加到节点时,我遇到错误。
要求是:
我想把它改成..
<?xml version="1.0"?>
<contacts>
<person>Adam</person>
<person>Eva</person>
<person>John</person>
<person>Thomas</person>
</contacts>
像这样
<?xml version="1.0"?>
<contacts>
<person>Adam</person>
<p>
<person>Eva</person>
</p>
<person>John</person>
<person>Thomas</person>
</contacts>
错误是
致命错误:未捕获的异常'DOMException',消息'Hierarchy Request Error'
我的代码是
function changeTagName($changeble) {
for ($index = 0; $index < count($changeble); $index++) {
$new = $xmlDoc->createElement("p");
$new ->setAttribute("channel", "wp.com");
$new ->appendChild($changeble[$index]);
$old = $changeble[$index];
$result = $old->parentNode->replaceChild($new , $old);
}
}
PHP中DOMDocument的错误层次结构请求错误意味着您正在尝试将节点移动到自身中。 在下图中将其与蛇相比较:
与您的节点类似。 您将节点移动到自身。 这意味着,当您想要用段落替换此人时,该人已经是该段落的子女。
appendChild()方法实际上已经将人移出DOM树,它不再是一部分:
$para = $doc->createElement("p");
$para->setAttribute('attr', 'value');
$para->appendChild($person);
<?xml version="1.0"?>
<contacts>
<person>Adam</person>
<person>John</person>
<person>Thomas</person>
</contacts>
伊娃已经走了。 它的parentNode已经是段落了。
所以相反,你首先要替换然后追加孩子:
$para = $doc->createElement("p");
$para->setAttribute('attr', 'value');
$person = $person->parentNode->replaceChild($para, $person);
$para->appendChild($person);
<?xml version="1.0"?>
<contacts>
<person>Adam</person>
<p attr="value"><person>Eva</person></p>
<person>John</person>
<person>Thomas</person>
</contacts>
现在一切都很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.