Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Can't remove node from DOMDocument

I Can't remove node from DOMDocument(get Exception):

My Code:

<?php
    function filterElements($htmlString) {
        $doc = new DOMDocument();
        $doc->loadHTML($htmlString);
        $nodes = $doc->getElementsByTagName('a');
        for ($i = 0; $i < $nodes->length; $i++) {
          $node=$nodes->item($i)
          if ($value->nodeValue == 'my_link') {
           $doc->removeChild($node);
          }
        }
    }
    $htmlString = '<div>begin..</div>this tool<a name="my_link">Beo</a> great!<div>.end</div>';
    filterKeyLinksElements($htmlString);
    ?>

Thanks, Yosef

like image 762
Ben Avatar asked Mar 03 '26 13:03

Ben


1 Answers

First off, what exception are you getting (It likely matters).

As for the specific problem, my guess would be as follows::

The $node is not a child of the document. It's a child of its parent. So you'd need to do:

$node->parentNode->removeChild($node);
like image 161
ircmaxell Avatar answered Mar 06 '26 02:03

ircmaxell