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.
bu开发者_如何转开发t 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.
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();
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
精彩评论