removing elements from xml with php

Go To StackoverFlow.com

0

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:

$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.

2012-04-05 01:37
by thebiglebowski11
This approach is not safe against multiple simultaneous requests. If two apps hit the php script at the same time, your xml file may be read while it is being written (thus being read as invalid xml). Consider using a real xml database, storing your xml in a relational database, or at least using file locking or atomic file writes - Francis Avila 2012-04-05 03:48
@FrancisAvila thank you for the input. The app will be used in a small graphical area and only few people will be able to update. However, it would be interesting to learn more.. Do you know of any good resources to get me up to speed - thebiglebowski11 2012-04-05 13:48


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.

2012-04-05 02:16
by Máthé Endre-Botond
Ads