简体   繁体   中英

Removing an xml node using php

I have an xml file like this:

<uploads>
 <upload>
  <name>asd</name>
  <type>123</name>
 </upload>
 <upload>
  <name>qwe</name>
  <type>456</name>
 </upload>
</uploads>

Now I want to delete a node upload that has a name child as (say qwe ). How can I delete it using php , so that the resulting xml is

<uploads>
 <upload>
  <name>asd</name>
  <type>123</name>
 </upload>
</uploads>

I do not have too much knowledge about xml and related techniques. Is it possible to do it using xpath, like this $xml->xpath('//upload//name') ? Assuming $xml was loaded using simplexml_load_file() function.

For reference, I was using this question to do what I want. But, it selects the element based on an attribute and I want to select an element based on the value of it child node.

Yes, you can use XPath to find the node that is to be removed. You can use predicates to specifiy the exact elements you're looking for. In your case the predicate can be has a name element and its (string/node) value is 'qwe' , like eg:

<?php
$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;
$doc->loadxml( getData() );

$xpath = new DOMXPath($doc);
foreach( $xpath->query("/uploads/upload[name='qwe']") as $node) {
    $node->parentNode->removeChild($node);
}
$doc->formatOutput = true;
echo $doc->savexml();


function getData() {
    return <<< eox
<uploads>
 <upload>
  <name>asd</name>
  <type>123</type>
 </upload>
 <upload>
  <name>qwe</name>
  <type>456</type>
 </upload>
</uploads>
eox;
}

prints

<?xml version="1.0"?>
<uploads>
  <upload>
    <name>asd</name>
    <type>123</type>
  </upload>
</uploads>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM