PHP add node to existing xml file and save
Solution 1
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.
Solution 2
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.
Solution 3
$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

Admin
Updated on June 28, 2022Comments
-
Admin 5 months
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. -
Ashith over 12 yearsDo 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?
-
chiborg over 12 yearsI 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.