使用htmlDOM解析HTML,将所有iframe代码替换为另一个 [英] Parse HTML with htmlDOM, replace all iframe tags with another

查看:464
本文介绍了使用htmlDOM解析HTML,将所有iframe代码替换为另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用html DOMDocument在$content变量中查找所有带iFrame的实例.我能够为每个实例输出一个图像,但宁愿将iframe替换为图像,然后再保存回content变量.与其echo而不是我的结果,我想替换当前的iframe.我该怎么做?

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;

推荐答案

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

这篇关于使用htmlDOM解析HTML,将所有iframe代码替换为另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆