使用DOMDocument用div包装所有图像 [英] Wrap all images with a div using DOMDocument

查看:57
本文介绍了使用DOMDocument用div包装所有图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的HTML文档,上面有几张图像.我想将所有图像包装在div.wrapped中.我将如何使用DOMDocument做到这一点?

I have a large html document, with several images. I want to wrap all the images inside div.wrapped. How would I do this with DOMDocument?

我已经看到了appendChild方法,但是该方法仅在末尾追加元素.如何在中间插入一个,然后在其中移动图像?

I've seen the appendChild method, but that only appends elements at the end. How can I insert one in the middle, and then move the image inside it?

推荐答案

我以前从未使用过DOMdocument,但我认为您的意思是这样的:

I never used DOMdocument before, but I think you mean something like this:

$html = <<<EOF
<html>
    <head>
        <title>:( -> :)</title>
    </head>
    <body>
        <img src="www.com" />
        <div class="random">
            <img src="www.ru" />
        </div>
    </body>
</html>
EOF;

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

//Create new wrapper div
$new_div = $dom->createElement('div');
$new_div->setAttribute('class','wrapper');

//Find all images
$images = $dom->getElementsByTagName('img');

//Iterate though images
foreach ($images AS $image) {
    //Clone our created div
    $new_div_clone = $new_div->cloneNode();
    //Replace image with this wrapper div
    $image->parentNode->replaceChild($new_div_clone,$image);
    //Append this image to wrapper div
    $new_div_clone->appendChild($image);
}

这篇关于使用DOMDocument用div包装所有图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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