SimpleXML: Deleting an XPath Node
In this article, we'll explore how to effectively delete a parent node from an XML document using SimpleXML and XPath.
Understanding SimpleXML's Limitations
The provided code attempts to use SimpleXML to delete a parent node after finding it via XPath. However, SimpleXML's unset() function only removes the object reference stored in a variable, not the node itself.
DOMDocument to the Rescue
To overcome SimpleXML's limitations, consider using DOMDocument, which manipulates the structure of XML documents more directly.
Solution Using DOMDocument
Example Code and Output
<code class="php">$doc = new DOMDocument; $doc->loadXML(...); $item_id = 456; $xpath = new DOMXpath($doc); foreach($xpath->query('//items[info/item_id="' . $item_id . '"]') as $node) { $node->parentNode->removeChild($node); } echo $doc->saveXML();</code>
This code removes the
Conclusion
DOMDocument allows for more robust manipulation of XML documents, including direct removal of nodes. While SimpleXML can be convenient for basic XPath queries, DOMDocument is a more suitable choice for more complex XML manipulation tasks.
The above is the detailed content of How Can I Delete an XPath Node Using SimpleXML and DOMDocument?. For more information, please follow other related articles on the PHP Chinese website!