SitePoint Sponsor |
|
User Tag List
Results 1 to 3 of 3
Thread: Update xml file or create
-
Jun 2, 2009, 15:55 #1
- Join Date
- Aug 2004
- Location
- Taunton, UK
- Posts
- 787
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Update xml file or create
I would like to update an xml file if it exists - if not then create it. I can do the creation bit but not sure how to add to it. I would like to add new characters.
My code is as folllows:
Code:$filename = XML_DIRECTORY.'characters.xml'; if (file_exists($filename)) { NOT SURE WHAT GOES HERE??? } else { echo "XML does not exist"; $file= fopen($filename, "w"); $xml_output = "<?xml version=\"1.0\"?>\n"; $xml_output .= "<characters>\n"; $xml_output .= "<character filename='$newname' characterName='$characterName' gender='$gender'></character>\n"; $xml_output .= "</characters>"; fwrite($file, $xml_output); fclose($file); }
PaulMediakitchen Limited
App Development | Website Design & Development | Flash Game Development
Somerset, UK
http://www.mediakitchen.co.uk
-
Jun 2, 2009, 16:05 #2
- Join Date
- Jul 2008
- Posts
- 5,757
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
http://www.php.net/manual/en/functio...t-addChild.php
You could do it by hand using string parsing, but it's more error prone. If you're going to be working with xml much, you should learn some of the tools to work with it.
-
Jun 2, 2009, 23:56 #3
- Join Date
- Aug 2004
- Location
- Taunton, UK
- Posts
- 787
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Thanks malibu
I have managed to muddle together a solution
Code:// ------------------ // Now write xml file // ------------------ $filename = XML_DIRECTORY.'characters.xml'; if (file_exists($filename)) { $xml = simplexml_load_file($filename); //This line will load the XML file. $sxe = new SimpleXMLElement($xml->asXML()); //In this line it create a SimpleXMLElement object with the source of the XML file. //The following lines will add a new child and others child inside the previous child created. $character = $sxe->addChild("character"); $character->addChild("characterName", $characterName); $character->addChild("gender", $gender); $character->addChild("filename", $newname); //This next line will overwrite the original XML file with new data added $sxe->asXML($filename); } else { $xmltext = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<characters></characters>"; $xmlobj = simplexml_load_string($xmltext); $characterobj = $xmlobj->addChild("character"); $characterobj->addChild("characterName", $characterName); $characterobj->addChild("gender", $gender); $characterobj->addChild("filename", $newname); $xmlobj->asXML($filename); }
Mediakitchen Limited
App Development | Website Design & Development | Flash Game Development
Somerset, UK
http://www.mediakitchen.co.uk
Bookmarks