开发者

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 :


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜