How to delete element with DOMDocument?

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


Easily:

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

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