PHP appendChild给出了很好的致命错误 - 未捕获异常' DOMException'消息'层次结构请求错误 - 如何在标记后添加html

时间:2012-07-12 13:19:13

标签: php dom appendchild

在我的代码中,我试图使用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>

这是PHP,我 bastardising 尝试:

$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变量的所有内容都可以正常工作。好吧,至少它没有错误。这是杀死它的最后四行。

我显然做了一些相对愚蠢的事情......那里有可爱的,可爱的人能够指出我在哪里冲洗过的东西?

1 个答案:

答案 0 :(得分:1)

首先:

您正尝试在此处附加图像并将图像添加到图像中(当然,在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);
}