in my laravel app I want to use DOMDocument to replace node values of each paragraph element by new values, for this I’m looping through each p element and replacing it with a new element, however I’m getting the following error:
Not Found Error, DOMException
On this line:
$dom->replaceChild($newNode, $pnode);
My method:
$htmlString =
'<section>
<h2>Introducción</h2>
<p>Primer acto</p>
<p>Segundo acto</p>
<p>Tercer acto</p>
<p>Climax</p>
<p>A volar</p>
</section>';
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($htmlString);
foreach( $dom->getElementsByTagName("p") as $pnode )
{
$result = 'New Translated Value';
$newNode = $dom->createElement("p", $result);
$dom->replaceChild($newNode, $pnode);
usleep( 500000 );
}
$dom->saveHTML($dom);
Thanks in advance!
2
Answers
The error message "Not Found Error, DOMException" on the line
$dom->replaceChild($newNode, $pnode);
means that the $pnode element is not found in the current DOM document, for this reason the replaceChild() method cannot replace it with the new element $newNode.This error may occur if the getElementsByTagName() method does not return any
elements in the DOM document. To check if this is the case, you can add a simple if statement to verify that the $pnode variable is not null before attempting to replace it with a new node.
This is the new code with the check added:
This should work!
You can use
$pnode->replaceWith()
to replace the node with other nodes.