David
David

Reputation: 41

PHP add node to existing xml file and save

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.

Upvotes: 4

Views: 15948

Answers (4)

Emmanuel
Emmanuel

Reputation: 21

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

This work perfectly well. And you can can add attributes to the burger too

Upvotes: 2

chiborg
chiborg

Reputation: 28074

The general problem here is that a well-formed XML document must have only one root element. That means you have to read/parse in the complete document tree for being able to add a new element inside. Hence all the simplexml suggestions here.

XMLWriter is meant for writing an XML stream of data very efficiently, but can't modify existing files (without reading them first).

See this thread on perlmonks.com where XML log files are discussed. Especially interesting is the comment by "mirod" that shows how to have a well-formed XML file and still be able to add nodes to a document. The solution is to place the arbitrary nodes in a separate file (that is not well-formed on its own because of the messing root element) and reference the file as an external entity. In your case, you'd write the file that will be included as an entity with the standard PHP fopen, fwrite fclose function while opening the file for appending.

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816334

You can use PHP's Simple XML. You have to read the file content, add the node with Simple XML and write the content back.

Upvotes: 2

Anthony
Anthony

Reputation: 37045

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.

Upvotes: 8

Related Questions