简体   繁体   中英

PHP appendChild giving nice fatal error -Uncaught exception 'DOMException' with message 'Hierarchy Request Error - how can I add html AFTER a tag

In my piece of code I'm trying to find all img tags using PHP DOM, add another img tag directly after and then wrap all of that in a div, ie

<!-- From this... -->
<img src="originalImage.jpg" />

<!-- ...to this... -->
<div class="wrappingDiv">
    <img src="originalImage.jpg" />
    <img src="newImage.jpg" />
</div>

This is the PHP that I'm bastardising trying:

$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();

Everything up to where I create the $added_img variable works fine. Well, at the very least it doesn't error. It's those last four lines that kill it dead.

I'm clearly doing something relatively idiotic... Any lovely, lovely people out there able to point out where I've douched things up?

First:

You are trying to append and image to an image here(but of course in HTML an image cannot have an child-image, append the images to the div):

$added_img = $image->appendChild($secondary_image);

it has to be

$added_img = $added_a->appendChild($secondary_image);

and again here:

$added_img->appendChild($image);

has to be:

$added_a->appendChild($image);

But this will not work at all, because NodeList's are live. As soon as you append one new image, this image is a part of $images, you will run into an infinite loop. So first populate an array with the initial images instead of using a NodeList.

$imageList= $dom->getElementsByTagName('img');
$images=array();
for($i=0;$i<$imageList->length;++$i)
{
  $images[]=$imageList->item($i);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM