用 htmlDOM 解析 HTML,用另一个替换所有 iframe 标签

Parse HTML with htmlDOM, replace all iframe tags with another

我正在使用 html DOMDocument 查找 iFrame w/in 和 $content 变量的所有实例。我能够为每个实例输出一个图像,但宁愿用图像替换 iframe,然后保存回内容变量。我不想 echoing 我的结果,而是想替换当前的 iframe。我该怎么做?

        $count = 1;
        $dom = new DOMDocument;
        $dom->loadHTML($content);
        $iframes = $dom->getElementsByTagName('iframe');
        foreach ($iframes as $iframe) {
            echo "<img class='iframe-".self::return_video_type($iframe->getAttribute('src'))." iframe-ondemand-placeholderImg iframe-".$count."' src='" .$placeholder_image. "' height='".$iframe->getAttribute('height')."' width='" .$iframe->getAttribute('width'). "' data-iframe-src='" .$iframe->getAttribute('src'). "' /><br />";
            $count++;
        }
        $content = $dom->saveHTML();

        return $content;
public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )

http://php.net/manual/en/domnode.replacechild.php

像这样:

$iframes = $dom->getElementsByTagName('iframe'); 
$i = $iframes->length - 1; 
while ($i > -1) { 
    $iframe = $iframes->item($i); 
    $ignore = false; 
    $img = $dom->createElement("img");
    $img->setAttribute("src",$iframe->getAttribute('src'));
    $iframe->parentNode->replaceChild($img, $iframe); 
    $i--; 
}