Home >Backend Development >PHP Tutorial >How to Remove an XPath Node in SimpleXML Without Losing the Entire Structure?
How to Remove an XPath Node with SimpleXML
Finding and removing an XML node using XPath queries can be a challenge in SimpleXML. This article addresses the issue of deleting a parent node identified through an XPath search.
Consider the following example:
<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>
In this code, the goal is to delete the parent
A solution is to revert to using DOMDocument for this task:
<code class="php">$doc = new DOMDocument; $doc->loadxml('<foo> <items> <info> <item_id>123</item_id> </info> </items> <items> <info> <item_id>456</item_id> </info> </items> <items> <info> <item_id>789</item_id> </info> </items> </foo>'); $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 will remove the
The above is the detailed content of How to Remove an XPath Node in SimpleXML Without Losing the Entire Structure?. For more information, please follow other related articles on the PHP Chinese website!