1

我需要读取一个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)
4

3 回答 3

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()文档

于 2013-04-06T23:38:29.413 回答
1

在 PHP 手册页(您应该始终排在第一位 :-) 中,一位出色的贡献者指出:

当您在 foreach 循环中迭代它们时,您无法从 DOMNodeList 中删除 DOMNode。

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

  <?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);
    }
    ?>
于 2013-04-06T06:56:24.443 回答
1

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

然后,在 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

于 2013-04-06T23:30:07.507 回答