How to Remove a Parent Node in SimpleXML Using XPath?
Oct 26, 2024 pm 12:56 PMSimpleXML - Removing XPath Nodes
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 <items> node.
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 <items> nodes, removes the parent node, and updates the $doc object.
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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

11 Best PHP URL Shortener Scripts (Free and Premium)

Working with Flash Session Data in Laravel

Simplified HTTP Response Mocking in Laravel Tests

Build a React App With a Laravel Back End: Part 2, React

cURL in PHP: How to Use the PHP cURL Extension in REST APIs

12 Best PHP Chat Scripts on CodeCanyon
