0

i have a html document, eg.:

<html>
<img src="/path-to-img/foo1.jpg">
<p>some other things</p>
<img src="/path-to-img/foo2.jpg">
</html>

now, i want replace all image with a new image and wrap the old in a noscript tag, eg.:

<html>
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src="/path-to-img/foo1.jpg">
<noscript><img src="/path-to-img/foo1.jpg"></noscript>
<p>some other things</p>
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src="/path-to-img/foo2.jpg">
<noscript><img src="/path-to-img/foo2.jpg"></noscript>
</html>

it seems simple :) but not for me!

I have tried this:

<?php
function callback($htmlBuffer) {

    $doc = new DomDocument();
    $doc->preserveWhiteSpace = true;

    libxml_use_internal_errors(true);
    $doc->loadHTML($htmlBuffer);
    libxml_use_internal_errors(false);

    // search all image
    $images = $doc->getElementsByTagName('img');

    foreach ($images as $image) {

        $src = $image->getAttribute('src');

        /** @var $parent DOMElement */
        $parent = $image->parentNode;

        // clone the old image in a new image
        $newDoc   = new DOMDocument();
        $newImage = $newDoc->importNode($image, true);

        $newImage->setAttribute('src', 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
        $newImage->setAttribute('data-src', $src);
        $parent->appendChild($newImage); // Exception here!!!!

        // wrap the old image with a noscript tag
        $noscript = $doc->createElement('noscript');
        $parent->replaceChild($noscript, $image);
        $noscript->apendChild($image);
    }

    return $doc->saveHTML();
}

see online DEMO

the script raise a exceprion

Fatal error: Uncaught exception 'DOMException' with message 'Wrong Document Error'

I do not understand how to use DOMDocument

Simone Nigro
  • 4,717
  • 2
  • 37
  • 72
  • Are you trying to replace the DOM content *after* the page has loaded? Wouldn't an AJAX method be better? – Jay Welsh Jun 02 '16 at 12:22
  • @Jay is important replace the DOM before the page has loaded – Simone Nigro Jun 02 '16 at 12:25
  • 3
    you can use Jquery here:

    some other things

    – Jaspal Saini Jun 02 '16 at 12:40
  • I need a php solution – Simone Nigro Jun 02 '16 at 13:08

0 Answers0