Home >Backend Development >PHP Tutorial >How to Remove an XPath Node in SimpleXML Without Losing the Entire Structure?

How to Remove an XPath Node in SimpleXML Without Losing the Entire Structure?

Susan Sarandon
Susan SarandonOriginal
2024-10-26 00:21:02591browse

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 node for a specific product identified by its . However, using unset($parent) does not remove the node because it only eliminates the reference to the object stored in $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 node containing the specified from the XML document. It uses the removeChild() method to delete the node from its parent.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn