How to append to a XML file with PHP preferably wi

2019-01-09 08:04发布

问题:

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

回答1:

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.