我需要使用PHP删除XML文件的元素.它将通过ajax完成,我需要通过属性找到XML元素.
这是我的XML文件
<?xml version="1.0" encoding="utf-8"?>
<messages>
<message time="1248083538">
<name>Ben</name>
<email>Ben's Email</email>
<msg>Bens message</msg>
</message>
<message time="1248083838">
<name>John Smith</name>
<email>john@smith.com</email>
<msg>Can you do this for me?</msg>
</message>
</messages>
Run Code Online (Sandbox Code Playgroud)
所以我想说的是删除时间等于1248083838的元素.
到目前为止我一直在使用Simple XML,我刚刚意识到除了删除元素之外它可以做任何事情.
那我该怎么做呢?
Sal*_*lty 10
Dave Morgan的正确之处在于DOM类更强大,但如果您想坚持使用SimpleXML,请尝试在任何节点上使用unset()函数.例如unset($ simpleXMLDoc-> node1-> child1),它将从XML中删除.
您可以在PHP中使用DOM类.(http://us3.php.net/manual/en/intro.dom.php).
您需要将XML文档读入内存,使用DOM类进行操作,然后根据需要(http或文件)保存XML.
DOMNode是一个具有删除功能的对象(用于解决您的问题).
它比SimpleXML稍微复杂一点,但是一旦你习惯了它,它就会变得更加强大
(半截取自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();
?>
Run Code Online (Sandbox Code Playgroud)
这应该给你一些关于如何删除元素的想法.它将打印出没有该节点的XML.如果要将其发送到文件,只需将字符串写入文件即可.
归档时间: |
|
查看次数: |
39760 次 |
最近记录: |