PHP add node to existing xml file and save

Is it possible using php XMLWriter to insert a new node into an existing xml file and then save the file. It would be much more beneficial for me to actually create an enw file every time I want to update an xml file.

+5
source share
4 answers

I would use simplexml. I go out on a limb and assume that if you have an XML writer, you also have a simplex.

Let's see, to add a node, let's say 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 a file and you want to add a new pie, you should:

$desserts = new SimpleXMLElement;

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

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

Of course, this can be a lot more complicated than that. But as soon as you receive it, it is very useful.

+7

PHP Simple XML. , node Simple XML .

+2

, XML- . , / , . .

XMLWriter XML- , ( ).

perlmonks.com, XML. "mirod", , XML . , ( - messing) . , PHP fopen, fwrite fclose, .

0
$xml_doc = new DomDocument;

$xml_doc->Load('yourfilename.xml');

$desserts = $xml_doc->getElementsByTagName('desserts')->item(0);

$burger =$xml_doc->createElement('burger');

$desserts->appendChild($burger);

$done = $xml_doc->save("yourfilename.xml");

. .

-1

All Articles