duanpie4763 2013-04-06 06:06
浏览 209
已采纳

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

I need to read an XML file and delete all the elements named <images> and all the children associated. I have found similar old questions that did not work. What am I doing wrong? Is there a better method?

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条回答 默认 最新

  • duanliyi5997 2013-04-06 23:38
    关注

    I figured it out after a good night of sleep. It was quite simple actually.

    $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);
    

    Edit: You probably want to make it save directly:

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

    See SimpleXMLElement::asXML()Docs.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?