Removing an xml node using php

喜夏-厌秋 提交于 2019-12-25 02:15:38

问题


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>


来源:https://stackoverflow.com/questions/8615846/removing-an-xml-node-using-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!