用php从xml中删除元素

时间:2023-01-14 23:58:46

I am building an iphone app which allows people to update an xml file by sending a POST to a php script. After they send the post to the php script and the xml is updated, I would like the user to be able to cancel the update to the XML. How can I delete just one element from the XML and rewrite the XML file to the same location on the server (in other words, just the one element is now gone, everything else is the same)? To add an element I used code that looks like the following:

我正在构建一个iphone应用程序,它允许人们通过发送POST到PHP脚本来更新xml文件。在他们将帖子发送到php脚本并更新xml之后,我希望用户能够取消对XML的更新。如何从XML中只删除一个元素并将XML文件重写到服务器上的相同位置(换句话说,现在只有一个元素已经消失,其他一切都是相同的)?要添加元素,我使用的代码如下所示:

$xmlUrl = "Bars.xml"; // XML 
$xmlStr = file_get_contents($xmlUrl);
$xml = new SimpleXMLElement($xmlStr);
$bartenders = $xml->xpath('//Bartenders');
$new_bartender = $bartenders[$newBar_ID]->addChild('Bartender');
$new_bartender->fname = $newfname;
$new_bartender->lname = $newlname;
$new_bartender->imageURL = $newimageURL;
$new_bartender->shift = $newShift;
print_r($bartenders);

$xml->asXML('Bars.xml');

When I send the POST method to the php script, I have the element's attribute to identify which is to be deleted. Thanks for your help.

当我将POST方法发送到php脚本时,我有元素的属性来识别要删除的内容。谢谢你的帮助。

1 个解决方案

#1


1  

Possible duplicate of THIS.

这可能是重复的。

From your code snippet I don't really know what data is given. You could try to do either

从你的代码片段我不知道给出了什么数据。你可以尝试做任何一件事

unset($bartenders[$newBar_ID]);

or

要么

$bartenders->removeChild($bartenders[$newBar_ID]);

I guess... I wrote these based on code snippets google turned up, never tested them. Feel free to give me feedback if it works or not.

我猜...我根据谷歌出现的代码片段写了这些,从未测试过它们。如果有效,请随时给我反馈。

#1


1  

Possible duplicate of THIS.

这可能是重复的。

From your code snippet I don't really know what data is given. You could try to do either

从你的代码片段我不知道给出了什么数据。你可以尝试做任何一件事

unset($bartenders[$newBar_ID]);

or

要么

$bartenders->removeChild($bartenders[$newBar_ID]);

I guess... I wrote these based on code snippets google turned up, never tested them. Feel free to give me feedback if it works or not.

我猜...我根据谷歌出现的代码片段写了这些,从未测试过它们。如果有效,请随时给我反馈。