Question:
In SimpleXML, how can I delete a parent node associated with a specific element identified through XPath?
Problem Description:
Using the following code to find and remove an item with a specific item_id fails:
<code class="php">$xml = simplexml_load_file($filename); $data = $xml->xpath('//items/info[item_id="' . $item_id . '"]'); $parent = $data[0]->xpath("parent::*"); unset($parent);</code>
The unset($parent) statement does not eliminate the parent
Answer:
Directly calling unset() on an object variable ($parent in this case) only removes the object reference, not the node itself.
Solution Using DOMDocument:
<code class="php">$doc = new DOMDOcument; $doc->loadxml(...XML string...); $item_id = 456; $xpath = new DOMXPath($doc); foreach($xpath->query('//items[info/item_id="' . $item_id . '"]') as $node) { $node->parentNode->removeChild($node); }</code>
This loop iterates through matching
Output:
<code class="xml"><?xml version="1.0"?> <foo> <items> <info> <item_id>123</item_id> </info> </items> <items> <info> <item_id>789</item_id> </info> </items> </foo></code>
The above is the detailed content of How to Remove a Parent Node in SimpleXML Using XPath?. For more information, please follow other related articles on the PHP Chinese website!