Search code examples
phpxmldomdomdocument

php DOMDocument removeChild throws exception of not found


remove is failing with not found exception.

PHP Fatal error:  Uncaught DOMException: Not Found Error
$document = new \DOMDocument();
$raw = '
some text
<a href="sad" sometag="true">linkkkk</a>
more text
';
$document->loadHTML($raw);

$links = $document->getElementsByTagName('a');
$a = $links->item(0);

$document->removeChild($a);

Solution

  • You could remove it from the parentNode from $a

    $document = new \DOMDocument();
    $raw = '
    some text
    <a href="sad" sometag="true">linkkkk</a>
    more text
    ';
    $document->loadHTML($raw);
    
    $links = $document->getElementsByTagName('a');
    $a = $links->item(0);
    $a->parentNode->removeChild($a);