PHP komut dosyası kullanarak XML dosyasını yenilemek

3 Cevap php

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.

Benim PHP çok kötü, bu yüzden ben burada birisi iyi ayak koymak beni umuyoruz ...

Benim PHP komut dosyası:

<?php
$id = $_POST['id'];
$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST['year'];
$venue = $_POST['venue'];

$xml_file="gig.xml";
$fh = fopen($xml_file,'r');
$current_tag=" ";
function start_element($parser,$element_name,$element_attrs)
{
      $current_tag = $element_name;
      if($element_name == 'GIG' && $element_attrs["ID"] == $id)
      {
            echo 'gig ID =' . $id;
                                             // here the new info has to replace the old
      };
};
if($fh) {  
echo "&verify=success&"; 
} else {  
echo "&verify=fail&"; 
}
fclose($fh);
?> 

3 Cevap

Peki ben XML yapısını neye benzediğini bilmiyorum ama:

<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

Şimdi bunun yerine tüm bu veri noktaları kullanabileceğiniz özellikler ise $gig->attributes()->venue erişmek için.

Eğer bir yazı ile birden güncellemeler yaparak sürece döngü için gerek gerçekten var - bir XPath sorgusu ile herhangi bir kayda da alabilirsiniz. Eğer DOMDocument özelliğini kullanarak öyle özellikle - SimpleXML aynı zamanda çok hafif ve domBelgesi daha bu tür bir şey için kullanmak çok daha kolaydır.

Sen domdocument ile bir de xml dosyasını yüklemek isteyeceksiniz

<?
$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();
?>

kod denenmemiş, ama genel bir fikir