It's often necessary to manipulate the content of HTML documents loaded with DOMDocument. One common task is to remove elements from the DOM.
Consider the following code:
<code class="php">$dom = new DOMDocument('1.0', 'utf-8'); $dom->loadHTML($html); foreach($dom->getElementsByTagName('a') as $href) if($href->nodeValue == 'First') //delete</code>
How can the First element be removed from the DOM without creating a new document?
To remove a node, instruct the parent node to remove the child:
<code class="php">$href->parentNode->removeChild($href);</code>
Refer to the $parentNodeDocs property of DOMNode and removeChild()Docs method for further details.
The above is the detailed content of How to Delete Elements from a DOMDocument in PHP Without Creating a New Document?. For more information, please follow other related articles on the PHP Chinese website!