Parse HTML with htmlDOM, replace all iframe tags with another

半城伤御伤魂 提交于 2019-12-25 04:44:09

问题


I am using the html DOMDocument to find all instances of iFrames w/in a $content variable. I am able to output an image for each instance but would rather replace the iframe with the image and then save back to the content variable. Instead of echoing my result I would like to replace the current iframe. How do I do this?

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

回答1:


public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )

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

Something like this:

$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--; 
} 


来源:https://stackoverflow.com/questions/28118437/parse-html-with-htmldom-replace-all-iframe-tags-with-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!