简体   繁体   English

用子节点PHP替换DOMDocument父节点

[英]Replace DOMDocument Parent node with child node PHP

This is my HTML code and I wanna replace <a> tag with <img> tag using DOMDocument . 这是我的HTML代码,我想使用DOMDocument<a>标记替换为<img>标记。

<a href='xxx.com'><img src='yyy.jpg'></a>

Here is the PHP code: 这是PHP代码:

$newNode=cj_DOMinnerHTML($link); //$link refer to anchor tag 
$image_dom = new DOMDocument();
$image_dom->loadHTML($newNode);
$link->parentNode->replaceChild($image_dom, $link); //this replace making my parent node empty 

cj_DOMinnerHTML is function which return child nodes as HTML. cj_DOMinnerHTML是将子节点作为HTML返回的函数。

Hello_ mate. 你好伙伴。

If I understood you well you want to remove the <a> tags and I don't know what exactly your function cj_DOMinnerHTML is doing, but I see that your are passing instance of DOMDocument to replaceChild method as first argument which is wrong. 如果我很了解您,您想删除<a>标记,但我不知道您的函数cj_DOMinnerHTML到底在做什么,但是我看到您将DOMDocument实例作为第一个参数传递给replaceChild方法,这是错误的。 Refer to documentation to see how exactly is replaceChild working (it accepts two arguments of type DOMNode ). 请参考文档,以了解replaceChild工作原理(它接受DOMNode类型的两个参数)。 Anyway I give you a code snippet that is replacing the <a> tags. 无论如何,我给您一个替换<a>标记的代码段。 Please read the comments that I put in code and try to change the code for your use case. 请阅读我在代码中添加的注释,并尝试为您的用例更改代码。

$html = '
<div id="container">
    <a href="xxx.com"><img src="yyy.jpg"></a>
    <a href="aaa.com"><img src="aaa.jpg"></a>
    <a href="bbb.com"><img src="bbb.jpg"></a>
    <a href="ccc.com"><img src="ccc.jpg"></a>
    <a href="ddd.com"><img src="ddd.jpg"></a>
    <a href="eee.com"><img src="eee.jpg"></a>
</div>';

// load the dom document
$dom = new \DOMDocument();
if (!$dom->loadHTML($html)) {
    echo '<h2>Error handle this ...</h2>';
}

// instantiate DOMXPath object
$finder = new \DOMXPath($dom);

// get all <a> tags of element that has id="container"
$anchors = $finder->query("//*[contains(concat(' ', normalize-space(@id), ' '), 'container')]/descendant::a");

// loop through all <a>
foreach ($anchors as $a) {
    $parent = $a->parentNode;
    // the following row of code will actually remove the <a> tag
    $parent->replaceChild($a->childNodes->item(0), $a);
}

// show output
echo htmlspecialchars($dom->saveHTML());

OUTPUT 输出值

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> 
<html>
    <body>
        <div id="container"> 
            <img src="yyy.jpg"> 
            <img src="aaa.jpg"> 
            <img src="bbb.jpg"> 
            <img src="ccc.jpg"> 
            <img src="ddd.jpg"> 
            <img src="eee.jpg"> 
        </div>
    </body>
</html> 

I hope you will understand the code and you will be able to modify it to work for your needs. 希望您能理解该代码,并能够对其进行修改以适合您的需求。

Good luck friend! 祝你好运的朋友!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM