PHP DOMDocument:替换并包装元素

时间:2016-06-02 11:57:45

标签: php dom domdocument

我有一个HTML文档,例如:

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

现在,我想用新图像替换所有图像并将旧图像包裹在noscript标记中,例如:

<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>

看起来很简单:)但不适合我!

我试过这个:

<?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();
}

在线查看DEMO

脚本提出了一个例外

  

致命错误:未捕获的异常'DOMException',消息'错误的文档错误'

我不明白如何使用DOMDocument

0 个答案:

没有答案