How to delete element with DOMDocument?

Kin picture Kin · Mar 7, 2013 · Viewed 53.4k times · Source

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

Answer

hakre picture hakre · Mar 7, 2013

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: