viswanathan
viswanathan

Reputation: 1

Updating the XML file using PHP script

I'm making an interface-website to update a concert-list on a band-website. The list is stored as an XML file an has this structure :

I already wrote a script that enables me to add a new gig to the list, this was relatively easy... Now I want to write a script that enables me to edit a certain gig in the list. Every Gig is Unique because of the first attribute : "id" . I want to use this reference to edit the other attributes in that Node. My PHP is very poor, so I hope someone could put me on the good foot here... My PHP script :

Upvotes: 0

Views: 1634

Answers (2)

prodigitalson
prodigitalson

Reputation: 60413

Well i dunno what your XML structure looks like but:

<gig id="someid">
 <venue></venue>
 <day></day>
 <month></month>
<year></year>
</gig>

$xml = new SimpleXmlElement('gig.xml',null, true);
$gig = $xml->xpath('//gig[@id="'.$_POST['id'].'"]');
$gig->venue = $_POST['venue'];
$gig->month = $_POST['month'];
// etc..

$xml->asXml('gig.xml)'; // save back to file

now if instead all these data points are attributes you can use $gig->attributes()->venue to access it.

There is no need for the loop really unless you are doing multiple updates with one post - you can get at any specific record via an XPAth query. SimpleXML is also a lot lighter and a lot easier to use for this type of thing than DOMDOcument - especially as you arent using the feature of DOMDocument.

Upvotes: 2

Charles Ma
Charles Ma

Reputation: 49151

You'll want to load the xml file in a domdocument with

<?
$xml = new DOMDocument();
$xml->load("xmlfile.xml");
//find the tags that you want to update
$tags = $xml->getElementsByTagName("GIG");
//find the tag with the id you want to update
foreach ($tags as $tag) {
   if($tag->getAttribute("id") == $id) { //found the tag, now update the attribute
      $tag->setAttribute("[attributeName]", "[attributeValue]");
   }
}

//save the xml
$xml->save();
?>

code is untested, but it's a general idea

Upvotes: 1

Related Questions