50

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');
$dom->loadHTML($html);

foreach($dom->getElementsByTagName('a') as $href)
    if($href->nodeValue == 'First')
        //delete
Kin
  • 4,466
  • 13
  • 54
  • 106
  • possible duplicate of [PHP: Can't remove node from DomDocument](http://stackoverflow.com/questions/3602207/php-cant-remove-node-from-domdocument) – hakre Mar 07 '13 at 13:42

5 Answers5

117

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:

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836
  • 2
    Yes, there are not many options how to do that. I now added some links so to make it an actual answer, but this actually smells like a duplicate candidate. At least one should pick some good related question. – hakre Mar 07 '13 at 13:48
39

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

alexanderbird
  • 3,847
  • 1
  • 26
  • 35
17

Easily:

$href->parentNode->removeChild($href);
silkfire
  • 24,585
  • 15
  • 82
  • 105
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();
0

for remove tag or somthing.

removeChild($element->id());

full example:

$dom = new Dom;
$dom->loadFromUrl('URL');
$html = $dom->find('main')[0];
$html2 = $html->find('p')[0];
$span = $html2->find('span')[0];


$html2->removeChild($span->id());

echo $html2;
Mkurbanov
  • 197
  • 3
  • 13