将 DOMDocument 父节点替换为子节点 PHP



这是我的HTML代码,我想使用DOMDocument <img>标签替换<a>标签。

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

这是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是将子节点作为 HTML 返回的函数。

Hello_伴侣。

如果我很好地理解您,您想删除<a>标签,我不知道您的函数cj_DOMinnerHTML到底在做什么,但我看到您正在将DOMDocument实例传递给replaceChild方法作为第一个参数这是错误的。请参阅文档以了解replaceChild工作的确切情况(它接受两个类型 DOMNode 的参数(。无论如何,我给你一个替换<a>标签的代码片段。请阅读我在代码中输入的评论,并尝试为您的用例更改代码。

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

输出

<!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> 

我希望您能理解代码,并且您将能够对其进行修改以满足您的需求。

祝朋友好运!

最新更新