[英]Uncaught exception 'DOMException' with message 'Hierarchy Request Error'
[英]PHP appendChild giving nice fatal error -Uncaught exception 'DOMException' with message 'Hierarchy Request Error - how can I add html AFTER a tag
在我的代码段中,我试图使用PHP DOM查找所有img标签,然后在其后直接添加另一个img标签,然后将所有这些标签包装在div中,即
<!-- From this... -->
<img src="originalImage.jpg" />
<!-- ...to this... -->
<div class="wrappingDiv">
<img src="originalImage.jpg" />
<img src="newImage.jpg" />
</div>
这是我
bastardising
尝试PHP:
$dom = new domDocument;
$dom->loadHTML($the_content_string);
$dom->preserveWhiteSpace = false;
//get all images and chuck them in an array
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
//create the surrounding div
$div = $image->ownerDocument->createElement('div');
$image->setAttribute('class','main-image');
$added_a = $image->parentNode->insertBefore($div,$image);
$added_a->setAttribute('class','theme-one');
$added_a->appendChild($image);
//create the second image
$secondary_image = $image->ownerDocument->createElement('img');
$added_img = $image->appendChild($secondary_image);
$added_img->setAttribute('src', $twine_img_url);
$added_img->setAttribute('class', $twine_class);
$added_img->appendChild($image);
}
echo $dom->saveHTML();
直到我创建$ added_img变量的所有地方都可以正常工作。 好吧,至少它不会出错。 是最后四行杀死了它。
我显然在做一些相对愚蠢的事情……有任何可爱,可爱的人能够指出我在哪里做过什么?
第一:
您正在尝试在此处将图像附加到图像(但是在HTML中,图像当然不能具有子图像,请将图像附加到div):
$added_img = $image->appendChild($secondary_image);
它一定要是
$added_img = $added_a->appendChild($secondary_image);
再次在这里:
$added_img->appendChild($image);
必须:
$added_a->appendChild($image);
但这根本不起作用,因为NodeList处于活动状态。 追加一个新图像后,该图像即成为$ images的一部分,您将陷入无限循环。 因此,首先使用初始图像填充数组,而不使用NodeList。
$imageList= $dom->getElementsByTagName('img');
$images=array();
for($i=0;$i<$imageList->length;++$i)
{
$images[]=$imageList->item($i);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.