Search code examples
phpxmlsimplexmldomdocument

Add node to xml without simplexml or domdocument


My php version is 5.1.2 and I don't have access to simplexml's addChild function or ANY DomDocument stuff. Any ideas on how I can add a node in an xml file?

For example:

<?xml version='1.0'?>
<post>
<title>cool website</title>
<email>[email protected]</email>
<first>Victor</first>
<last>Chen</last>
<date>01/04/13</date>
<time>12:31 am</time>
<category>acm</category>
<content>gj</content>
</post>

I would like to add another node like above. What is the best way given my limitations?


Solution

  • If XMLReader and XMLWriter are available:

    1. Use an XMLReader object to copy everything over to a paired XMLWriter object until the point where you want to add the node.
    2. Add whatever nodes you want using the XMLWriter object.
    3. Continue copying until the end of the document.

    XMLReader and XMLWriter were added to PHP by default as of 5.1.2, but it's still possible they were disabled via compile-time flags.

    If not even these are available, you need to use an XMLParser and write out the XML (the XMLWriter part) very carefully yourself. The only thing I know for sure that you have based on your phpinfo is the XML parser.

    You really need to upgrade your PHP.