如何删除XML元素和所有子元素?

时间:2013-04-06 06:06:11

标签: php xml

我需要阅读XML文件并删除名为<images>的所有元素以及所有相关的子元素。我发现类似的旧问题没有用。我究竟做错了什么?有更好的方法吗?

XML:

<?xml version='1.0' encoding='UTF-8'?>
<settings>
  <background_color>#000000</background_color>
  <show_context_menu>yes</show_context_menu>
  <image>
    <thumb_path>210x245.png</thumb_path>
    <big_image_path>620x930.png</big_image_path>
  </image>
  <image>
    <thumb_path>200x295.png</thumb_path>
    <big_image_path>643x950.png</big_image_path>
  </image>
</settings>

PHP:

$dom = new DOMDocument();
$dom->load('test.xml');
$thedocument = $dom->documentElement;
$elements = $thedocument->getElementsByTagName('image');

foreach ($elements as $node) {
  $node->parentNode->removeChild($node);
}

$save = $dom->saveXML();
file_put_contents('test.xml', $save)

3 个答案:

答案 0 :(得分:2)

经过一夜安眠后,我想出来了。实际上很简单。

$xml = simplexml_load_file('test.xml');
unset($xml->image);
$xml_file = $xml->asXML();
$xmlFile = 'test.xml';
$xmlHandle = fopen($xmlFile, 'w');
fwrite($xmlHandle, $xml_file);
fclose($xmlHandle);

编辑:您可能希望直接保存:

$file = 'test.xml';

$xml = simplexml_load_file($file);
unset($xml->image);
$success = $xml->asXML($file);

请参阅SimpleXMLElement::asXML()Docs

答案 1 :(得分:1)

在PHP手册页(你应该总是第一位:-)中,一位很棒的贡献者指出:

  

You can't remove DOMNodes from a DOMNodeList as you're iterating over them in a foreach loop.

然后继续提供潜在的解决方案。尝试这样的事情:

  <?php
    $domNodeList = $domDocument->getElementsByTagname('p');
    $domElemsToRemove = array();
    foreach ( $domNodeList as $domElement ) {
      // ...do stuff with $domElement...
      $domElemsToRemove[] = $domElement;
    }
    foreach( $domElemsToRemove as $domElement ){
      $domElement->parentNode->removeChild($domElement);
    }
    ?>

答案 2 :(得分:1)

首先,您的XML已损坏,请参阅<thumb>...</thumb_path>和下一行 - &gt; 修复它!

然后,真正简单的3行代码:

$xml = simplexml_load_string($x); // $x holds your xml
$count = $xml->image->count()-1;
for ($i = $count;$i >= 0;$i--) unset($xml->image[$i]);

查看现场演示@ http://codepad.viper-7.com/HkGy5o