skip to Main Content

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


  1. 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:

    $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);
        
        // check if $pnode exists before replacing it
        if ($pnode) {
            $dom->replaceChild($newNode, $pnode);
        }
        
        usleep(500000);
    }
    
    // print the updated HTML
    echo $dom->saveHTML();
    
    

    This should work!

    Login or Signup to reply.
  2. You can use $pnode->replaceWith() to replace the node with other nodes.

    foreach ($dom->getElementsByTagName("p") as $pnode) {
        /** @var DOMElement $pnode */
        $result = 'New Translated Value';
    
        $newNode = $dom->createElement("p", $result);
    
        $pnode->replaceWith($newNode);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search