...">

How to add to XML file with PHP, preferably with SimpleXML

I have an XML file that 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 was trying to figure out how to add another <gallery> to my XML file above. I tried using simplexml but couldn't get it working, so I tried this one as well as a bunch of others in stackoverflow. But I just canโ€™t make it work.
I can easily read the XML file and get all the information I need. But I need to add a gallery tag to it. The code below does not work, and when it does, I can only insert one element, and it inserts it 3 times, I do not 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 have had many unsuccessful attempts, it should be so simple. Basically I want to add a gallery with the filepath file name and thumb to the same file (xml / config.php).

As I said, I somehow earned, but unformatted and does not have a gallery tag.

Question
How to insert another <gallery> (with children) into the above XML file?
Even using simpleXML is preferable

+7
source share
1 answer

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

Keep in mind that SimpleXML will not โ€œformatโ€ XML for you, however, moving from an unformatted representation of SimpleXML to neatly deferred XML is not a difficult step and a lot of questions are addressed here.

+14
source

All Articles