Home  >  Article  >  Backend Development  >  How do I delete nodes from an XML document using SimpleXML and DOMDocument in PHP?

How do I delete nodes from an XML document using SimpleXML and DOMDocument in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-10-31 06:15:38986browse

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:

  1. Load the XML document into a SimpleXMLElement object.
  2. Use the xpath() method to search for the desired node.
  3. Store the result in a variable, e.g., $data.

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:

  1. Create a new DOMDocument object and load the XML document.
  2. Use the xpath() method to search for the desired node.
  3. Remove the node using parentNode->removeChild($node).

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!

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