9

I have a XML file which looks like this:

<?xml version="1.0" encoding="utf-8"?>
<data>
    <config>
    </config>

    <galleries>
         // We have loads of these <gallery>
         <gallery>
             <name>Name_Here</name>
             <filepath>filepath/file.txt</filepath>
             <thumb>filepath/thumb.png</thumb>
         </gallery>
    </galleries>
</data>

I have been trying to figure out how to append another < gallery > to my above xml file. I tried using simplexml but couldn't get it to work, so I tried this answer as well as a bunch of others on stackoverflow. But just cant get it to work.
I can read from a xml file easily and get all the info I need, But I need to be able to append a gallery tag to it, The code below doesnt work and when it does, I can only insert 1 element, and it inserts it 3 times, i dont understand this.

 $data = 'xml/config.xml';
 // Load document
 $xml = new DOMDocument;
 $xml->load( $data ); #load data into the element

 $xpath = new DOMXPath($xml);
 $results = $xpath->query('/data/galleries');
 $gallery_node = $results->item(0);

 $name_node = $xml->createElement('name');
 $name_text = $xml->createTextNode('nametext');

 $name_node = $name_node->appendChild($name_text);

 $gallery_node->appendChild($name_node);

 echo $xml->save($data);

I've had loads of failed attempts at this, this should be so easy. Basically I want to add a gallery with childs name filepath and thumb to this same file (xml/config.php).

Like I said, I kinda got it to work, but its unformatted and a doesnt have the gallery tag.

Question
How do I insert another < gallery > (with children) into the above XML file?
Preferably even using simpleXML

Community
  • 1
  • 1

1 Answers1

18

With SimpleXML, you can use the addChild() method.

$file = 'xml/config.xml';

$xml = simplexml_load_file($file);

$galleries = $xml->galleries;

$gallery = $galleries->addChild('gallery');
$gallery->addChild('name', 'a gallery');
$gallery->addChild('filepath', 'path/to/gallery');
$gallery->addChild('thumb', 'mythumb.jpg');

$xml->asXML($file);

Be aware that SimpleXML will not "format" the XML for you, however going from an unformatted SimpleXML representation to neatly indented XML is not a complicated step and is covered in lots of questions here.

salathe
  • 51,324
  • 12
  • 104
  • 132
  • This works! but it outputs it 3 times in my xml, any ideas why it would do this? it outputs 3 sets of and children on the same line, It did this with my above script aswell? any clues? – Anil Aug 17 '11 at 19:25
  • 2
    You're probably doing something wrong in a loop. Nothing you've shown, or I've given, will repeat the gallery element three times. – salathe Aug 17 '11 at 19:27
  • Looking at a particular RSS feed at the moment and it seems to be the convention there that the newer entry is added above the others rather than below. Is it possible to specify that when writing the node/"gallery"? – TenLeftFingers Aug 01 '19 at 23:02