PHP appendChild给出漂亮的致命错误-未捕获异常';DOMException';带有消息'


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>

这是我正在尝试的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变量的地方,一切都很好。至少它不会出错。是最后四行字把它弄死了。

我显然在做一些相对愚蠢的事情。。。有没有可爱的人能指出我把事情搞砸了?

第一个:

您试图在此处将和image附加到图像(但在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);
}