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
some other things