ajsie
ajsie

Reputation: 79686

use DOMdocument to append elements in a XML-file?

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.

Upvotes: 1

Views: 3831

Answers (2)

Alana Storm
Alana Storm

Reputation: 166066

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 fetched 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();

Upvotes: 4

Ross Snyder
Ross Snyder

Reputation: 1975

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

Upvotes: 2

Related Questions