tags:

views:

29

answers:

2

i'm using the DOMdocument class in php whenever i want to create a XML document.

but how could i open a XML document and add elements after an existing element in the XML document?

its a very huge XML-document so it would be great to consider the most efficient way to do this.

+2  A: 

If I'm not mistaken, DOMDocument attempts to load all of the XML into memory. If it's huge, it could kill efficiency and take down your PHP process. I ran into this once and had to switch from DOMDocument to XML Parser, which is callback-based, so you can read your XML line-by-line and respond to tags as you see fit:

http://www.php.net/manual/en/book.xml.php

beamrider9
+1  A: 

If you're sticking with DOMdocument, appending a new node is as simple as getting a reference to an existing node, creating child nodes, and then appending new nodes to those children. I've used XPath below, but any method that returns a DOMNode should work. The important part to remember is even though you've fetch a part of the tree, internally it's part of the original DOMDocument.

$xml = new DomDocument();
$xml->loadXml('<foo><baz><bar>Node Contents</bar></baz></foo>');    

//grab a node
$xpath = new DOMXPath($xml);    
$results = $xpath->query('/foo/baz');   
$baz_node_of_xml = $results->item(0);

//create a new, free standing node  
$new_node = $xml->createElement('foobazbar');

//create a new, freestanding text node
$text_node = $xml->createTextNode('The Quick Brown Fox');

//add our text node
$new_node->appendChild($text_node);

//append our new node to the node we pulled out
$baz_node_of_xml->appendChild($new_node);

//output original document.  $baz_nod_of_xml is
//still considered part of the original $xml DomDocument
echo $xml->saveXML();
Alan Storm
does this method read the whole XML DOM tree into memory? cause the file is very huge...
weng
I'm not sure how the internal of DOMDocument work. One one hand, most tree based parsers DO read the entire document into memory. On the other other hand, when you try to print_r or var_dump a DOMDocument object, you only see a fraction of all available nodes. Give it a try, and if it performs well you're good to go, f not look into XMLParser or XMLReader.
Alan Storm