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

Susan Sarandon
Release: 2024-10-31 06:15:38
Original
985 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!