如何使用php dom文档删除和替换标签

时间:2013-07-28 17:04:03

标签: php image dom

我有图片代码<img src="path_to_file.png">,但我希望将图片代码转换为移动网站中的链接。 所以我想将img转换为href:

<a href="path_to_file.png" target="_blank">Click here to open in new tab</a>

我开始使用php dom。 我可以列出所有属性。

$newdocument = new DOMDocument();
$newdocument->loadHTML();
$getimagetag = $doc->getElementsByTagName('img');
foreach($getimagetag as $tag) {
    echo $src=$tag->getAttribute('src');
}

但我们如何获取src属性,然后完全删除img标签,因为它包含其他参数,如高度和长度,然后创建新的链接标记?

大家好我可以使用以下代码

从php dom完成
$input="<img src='path_to_file.png' height='50'>";
    $doc = new DOMDocument();
    $doc->loadHTML($input);
    $imageTags = $doc->getElementsByTagName('img');
    foreach($imageTags as $tag) {
        $src=$tag->getAttribute('src'); 
        $a=$doc->createElement('a','click here to open in new tab');
        $a->setAttribute('href',$src);
        $a->setAttribute('style','color:red;');
        $tag->parentNode->replaceChild($a,$tag);
        } 
        $input=$doc->saveHTML();
echo $input; 

create元素还可用于在<a></a>之间放置文本,即点击...新标签。

replacechild用于删除$ tag,即img,并将其替换为a标记。 通过设置属性,我们可以添加其他参数,如样式,目标等。

我最后使用了php dom因为我只想要从mysql获取的数据被转换而不是像网站徽标那样的其他元素。当然,也可以使用javascript。

由于

@dave chen javascript方式并指向检测移动链接。

@nate指示我回答。

2 个答案:

答案 0 :(得分:3)

使用phpQuery,这太棒了。就像使用jquery一样! :) https://code.google.com/p/phpquery/

答案 1 :(得分:2)

我建议使用JavaScript执行此操作:

<!DOCTYPE html>
<html>
<head>
    <title>Images Test</title>
    <script>
        window.onload = changeImages;

        function changeImages() {
            var images = document.getElementsByTagName("img");

            while (images.length > 0) {
                var imageLink       = document.createElement("a");
                imageLink.href      = images[0].src;
                imageLink.innerHTML = "Click here to view " + images[0].title;
                images[0].parentNode.replaceChild(imageLink, images[0]);
            }
        }
    </script>
</head>
<body>
    Here is a image of flowers  : <img src="images/flowers.bmp"   title="Flowers"  ><br>
    Here is a image of lakes    : <img src="images/lakes.bmp"     title="Lakes"    ><br>
    Here is a image of computers: <img src="images/computers.bmp" title="Computers"><br>
</body>
</html>

Example