Removing Elements with DOMDocument
In PHP, you can easily load and manipulate HTML documents using the DOMDocument class. However, you may encounter a need to remove elements from the loaded DOM, and this document will guide you through this process without creating a new DOM.
To delete an element from the DOMDocument, the parent node's removeChild() method must be employed. Here's how to do it:
<code class="php"><?php $dom = new DOMDocument('1.0', 'utf-8'); $dom->loadHTML($html); foreach($dom->getElementsByTagName('a') as $href) { if($href->nodeValue == 'First') $href->parentNode->removeChild($href); } ?></code>
In this code, the removeChild() method is called on the parent node of the element to be deleted. The parentNode property of a DOMNode object references the parent node, and the removeChild() method removes the specified child node from the parent.
By utilizing the parentNode->removeChild() method, you can effectively remove elements from the DOM, allowing you to modify the structure of the loaded HTML document.
The above is the detailed content of How to Remove Elements from a DOMDocument in PHP Without Creating a New One?. For more information, please follow other related articles on the PHP Chinese website!