0

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 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.