Home » Php » How to append to a XML file with PHP preferably with SimpleXML

How to append to a XML file with PHP preferably with SimpleXML

Posted by: admin July 12, 2020 Leave a comment


I have a XML file which looks like this:

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

         // We have loads of these <gallery>

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);


 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.

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

How to&Answers:

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');


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.