Search code examples
phpdomdocument

How to delete element with DOMDocument?


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

Solution

  • 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: