繁体   English   中英

php的DOMDocument

[英]DOMDocument with php

我想替换HTML上的所有图像,但代码替换一个并转义一个,依此类推

我使用DOMDocument替换内容中的图像,然后使用下一个代码,问题是例如代码转义图像

1 2 3 4图片代码替换了1和3并转义了拖曳4和以此类推

见成效

    $dom = new \DOMDocument();
    $dom->loadHTML("data"));
    $dom->preserveWhiteSpace = true;
    $count = 1;

    $images = $dom->getElementsByTagName('img');
    foreach ($images as $img) {

        $src =   $img->getAttribute('src');
        $newsrc = $dom->createElement("newimg");
        $newsrc->nodeValue = $src;
        $newsrc->setAttribute("id","qw".$count);
        $img->parentNode->replaceChild($newsrc, $img);
        $count++;

    }

    $html = $dom->saveHTML();
    return $html;

的HTML代码是

 <p><img class="img-responsive"  src="http://www.jarofquotes.com/img/quotes/86444b28aa86d706e33246b823045270.jpg" alt="" width="600" height="455" /></p>
 <p>&nbsp;</p>
 <p>some text</p>
 <p>&nbsp;</p>
 <p><img class="img-responsive" src="http://40.media.tumblr.com/c0bc20fd255cc18dca150640a25e13ef/tumblr_nammr75ACv1taqt2oo1_500.jpg" alt="" width="480" height="477" /></p>
 <p>&nbsp;</p>
 <p><span class="marker"><img class="img-responsive" src="http://wiselygreen.com/wp-content/uploads/green-living-coach-icon.png" alt="" width="250" height="250" /><br /><br /></span></p>

我想输出html替换所有图像

   <newimg>Src </newimg>

好的,我找不到适合PHP的dupe,所以我正在回答这个问题。

您面临的问题是getElementsByTagName()返回的NodeList是活动列表。 这意味着,当您调用replaceChild() ,您正在更改当前正在迭代的NodeList。

假设我们有以下HTML:

$html = <<< HTML
<html>
    <body>
        <img src="1.jpg"/>
        <img src="2.jpg"/>
        <img src="3.jpg"/>
    </body>
</html>
HTML;

现在,将其加载到DOMDocument并获取img元素:

$dom = new DOMDocument;
$dom->loadHTML($html);

$allImages = $dom->getElementsByTagName('img');
echo $allImages->length, PHP_EOL;

这将打印3,因为DOM中现在有3个img元素。

让我们用p元素替换第一个img元素:

$allImages->item(0)->parentNode->replaceChild(
    $dom->createElement("p"),
    $allImages->item(0)
);
echo $allImages->length, PHP_EOL;

现在给出2,因为现在只剩下2个img元素

item 0: img will be removed from the list
item 1: img will become item 0
item 2: img will become item 1

您正在使用foreach ,因此首先要替换项目0,然后移至项目1,但是项目1现在是项目2,项目0是您接下来要期待的项目1。 但是由于列表是实时的,因此您将跳过它。

要解决此问题,请使用while循环,并始终替换第一个元素:

while ($allImages->length > 0) {
    $allImages->item(0)->parentNode->replaceChild(
        $dom->createElement("p"),
        $allImages->item(0)
    );
}

然后将捕获所有img元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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