Replace DOMDocument Parent node with child node PHP
Get the solution ↓↓↓Solution:
Hello_ mate.
If I understood you well you want to remove the<a>
tags and I don't know what exactly your functioncj_DOMinnerHTML
is doing, but I see that your are passing instance ofDOMDocument
toreplaceChild
method as first argument which is wrong. Refer to to see how exactly isreplaceChild
working (it accepts two arguments of typeDOMNode
). Anyway I give you a code snippet that is replacing the<a>
tags. 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!
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: unable to determine current zabbix database version: the table "dbversion" was not found.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.