How to delete element with DOMDocument?

  • Added:
  • |
  • In: Basic PHP

Is it possible to delete element from loaded DOM without creating a new one? For example something like this:

$dom = new DOMDocument('1.0', 'utf-8');

foreach($dom->getElementsByTagName('a') as $href)
    if($href->nodeValue == 'First')
This Question Has 3 Answeres | Orginal Question | Kin

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


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

See as well:

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);

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



Meet with owner

Sajjad Hossain

Hey, I am Sajjad, working in web development sector since 2012. I love to do amazing things. Let's do a project together.
Connect Social With PHPAns