Removing an xml node using php

2019-09-11 01:22发布

问题:

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.

回答1:

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 e.g.:

<?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>