tags:

views:

423

answers:

3

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 benficial to me that actually creating a enw file every time i want to update an xml file.

+2  A: 

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.

Felix Kling
+3  A: 

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.

Anthony
A: 

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.

chiborg
Do most XML parsers understand/handle reference files well enough to rely on this solution? And is this idea of linked nodes not being validated a pretty safe and understood idea? I could see how it would be, if the browser/client/parser only goes downstream from the reference, but is there some chance that to protect against malformed references that it will need to validate the whole document first? or does it just need to be valid in context of the primary xml document?
Anthony
I don't know many XML parsers to know if "most" parsers support entity expansion. I mostly work with PHP and the PHP XML parser (a wrapper around xmllib) supports it. After the inclusion, the full document must be well-formed. I'll edit my answer to reflect that.
chiborg