How to delete element with DOMDocument?
Asked Answered
U

5

52

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
Untuck answered 7/3, 2013 at 13:41 Comment(1)
possible duplicate of PHP: Can't remove node from DomDocumentGroundless
G
122

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:

Groundless answered 7/3, 2013 at 13:43 Comment(1)
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.Groundless
R
44

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

Rosenzweig answered 2/12, 2015 at 7:43 Comment(1)
You saved me a lot of head scratching. Thanks!Apostolic
T
18

Easily:

$href->parentNode->removeChild($href);
Thegn answered 7/3, 2013 at 13:43 Comment(0)
D
5

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();
Daybreak answered 20/2, 2020 at 15:43 Comment(1)
Yes. This is very important. php.net/manual/en/domnode.removechild.php#90292Super
F
1

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;
Footstall answered 12/1, 2021 at 6:15 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.