Deleting Elements with DOMDocument
Manipulating HTML documents is a common task for web developers. In PHP, the DOMDocument class provides a convenient way to parse and manipulate HTML code. While it's possible to create a new DOMDocument from scratch, in many cases it's more efficient to load an existing document into a DOMDocument object.
One of the most common operations when modifying an HTML document is removing elements. Let's consider the following HTML code:
<code class="html"><p><a href="#">First</a></p> <p><a href="#">Second</a></p> <p><a href="#">Third</a></p></code>
Q: Is it possible to delete an element in a loaded DOMDocument without creating a new one?
<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>
A: Yes, it is possible to delete an element from a loaded DOMDocument without creating a new one:
<code class="php">$href->parentNode->removeChild($href);</code>
This approach modifies the original DOMDocument object directly. The DOMNode::$parentNode property references the parent node of the current node, and the DOMNode::removeChild() method removes the specified child node from the parent node.
Additional resources for working with DOMDocuments:
The above is the detailed content of Can You Delete Elements in a Loaded DOMDocument Without Creating a New One?. For more information, please follow other related articles on the PHP Chinese website!