![](/img/trans.png)
[英]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.