Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP add node to existing xml file and save

Tags:

php

xml

Is it possible using php's XMLWriter to insert a new node to an existing xml file, and then save the file? This would be much more beneficial to me that actually creating a new file every time I want to update an xml file.

like image 653
David Avatar asked Dec 23 '22 04:12

David


1 Answers

I would use simplexml instead. I'm going out on a limb and assuming that if you have XML writer you have simplexml as well.

Let's see, to add a node, let's assume a very simple (get it?) xml file:

 <desserts>
     <cakes>
        <cake>chocolate</cake>
        <cake>birthday</cake>
     </cakes>
     <pies>
        <pie>apple</pie>
        <pie>lemon</pie>
     </pies>
</desserts>

If this is in a file, and you want to add a new pie, you would do:

$desserts = new SimpleXMLElement;

$desserts->loadfile("desserts.xml");

$desserts->pies->addChild("pie","pecan");

It can be much more sophisticated than this, of course. But once you get the hang of it, it's very useful.

like image 200
Anthony Avatar answered Jan 08 '23 09:01

Anthony