How to delete element with DOMDocument?

Solution 1:

You remove the node by telling the parent node to remove the child:

$href->parentNode->removeChild($href);

See DOMNode::$parentNodeDocs and DOMNode::removeChild()Docs.

See as well:

  • How to remove attributes using PHP DOMDocument?
  • How to remove an HTML element using the DOMDocument class

Solution 2:

This took me a while to figure out, so here's some clarification:

If you're deleting elements from within a loop (as in the OP's example), you need to loop backwards

$elements = $completePage->getElementsByTagName('a');
for ($i = $elements->length; --$i >= 0; ) {
  $href = $elements->item($i);
  $href->parentNode->removeChild($href);
}

DOMNodeList documentation: You can modify, and even delete, nodes from a DOMNodeList if you iterate backwards

Solution 3:

Easily:

$href->parentNode->removeChild($href);

Solution 4:

I know this has already been answered but I wanted to add to it.

In case someone faces the same problem I have faced.

Looping through the domnode list and removing items directly can cause issues.

I just read this and based on that I created a method in my own code base which works:https://www.php.net/manual/en/domnode.removechild.php

Here is what I would do:

$links = $dom->getElementsByTagName('a');
$links_to_remove = [];

foreach($links as $link){
    $links_to_remove[] = $link;
}

foreach($links_to_remove as $link){
    $link->parentNode->removeChild($link);
}

$dom->saveHTML();