且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP-删除XML元素

更新时间:2023-02-23 17:21:08

您可以在PHP中使用DOM类. ( http://us3.php.net/manual/en/intro.dom. php ).

You can use the DOM classes in PHP. ( http://us3.php.net/manual/en/intro.dom.php ).

您将需要将XML文档读入内存,使用DOM类进行操作,然后可以根据需要保存XML(保存到http或文件).

You will need to read the XML document into memory, use the DOM classes to do manipulation, and then you can save out the XML as needed (to http or to file).

DOMNode是其中具有删除功能(以解决您的问题)的对象.

DOMNode is an object in there that has remove features (to address your question).

它比SimpleXML复杂一点,但是一旦您习惯了它,它的功能就会强大得多

It's a little more complicated than SimpleXML but once you get used to it, it's much more powerful

(半取自php.net的代码示例)

(semi-taken from a code example at php.net)

<?php

$doc = new DOMDocument; 
$doc->load('theFile.xml');

$thedocument = $doc->documentElement;

//this gives you a list of the messages
$list = $thedocument->getElementsByTagName('message');

//figure out which ones you want -- assign it to a variable (ie: $nodeToRemove )
$nodeToRemove = null;
foreach ($list as $domElement){
  $attrValue = $domElement->getAttribute('time');
  if ($attrValue == 'VALUEYOUCAREABOUT') {
    $nodeToRemove = $domElement; //will only remember last one- but this is just an example :)
  }
}

//Now remove it.
if ($nodeToRemove != null)
$thedocument->removeChild($nodeToRemove);

echo $doc->saveXML(); 
?>

这应该使您对如何删除元素有一些了解.它将在没有该节点的情况下打印出XML.如果要将其发送到文件,只需将字符串写入文件.

This should give you a little bit of an idea on how to remove the element. It will print out the XML without that node. If you wanted to send it to file, just write the string to file.