Home > Article > Backend Development > How do I delete nodes from an XML document using SimpleXML and DOMDocument in PHP?
Deleting Nodes in SimpleXML
Querying XPath Nodes
To delete a node in SimpleXML using XPath, follow these steps:
Node Removal
To remove the parent node of the selected node, you cannot use unset($parent). Instead, you need to use the __unset() method or revert to DOMDocument.
Using __unset()
The __unset() method is called when you try to unset a property of an object. To remove a node using __unset(), create a new SimpleXMLElement object and unset the desired node, as shown below:
<code class="php">$newNode = new SimpleXMLElement('<a><b></b></a>'); unset($newNode->b); echo $newNode->asxml(); // Prints <a></a></code>
Using DOMDocument
DOMDocument provides more detailed control over XML manipulation. To remove a node using DOMDocument:
Example with DOMDocument
<code class="php">$doc = new DOMDocument; $doc->loadxml('<foo><items><info><item_id>123</item_id></info></items></foo>'); $item_id = 123; $xpath = new DOMXpath($doc); foreach ($xpath->query('//items[info/item_id="' . $item_id . '"]') as $node) { $node->parentNode->removeChild($node); } echo $doc->savexml(); // Prints <foo><items><info><item_id>123</item_id></info></items></foo></code>
By using these techniques, you can effectively remove nodes from XML documents using SimpleXML and DOMDocument.
The above is the detailed content of How do I delete nodes from an XML document using SimpleXML and DOMDocument in PHP?. For more information, please follow other related articles on the PHP Chinese website!