12.2. Generating XML with the DOM
Problem
You want to generate XML but want to
do it in an organized way instead of using print
and loops.
Solution
Use
PHP’s DOM XML extension
to create a DOM object; then, call dump_mem( )
or dump_file( )
to generate a well-formed XML document:
// create a new document $dom = domxml_new_doc('1.0'); // create the root element, <book>, and append it to the document $book = $dom->append_child($dom->create_element('book')); // create the title element and append it to $book $title = $book->append_child($dom->create_element('title')); // set the text and the cover attribute for $title $title->append_child($dom->create_text_node('PHP Cookbook')); $title->set_attribute('cover', 'soft'); // create and append author elements to $book $sklar = $book->append_child($dom->create_element('author')); // create and append the text for each element $sklar->append_child($dom->create_text_node('Sklar')); $trachtenberg = $book->append_child($dom->create_element('author')); $trachtenberg->append_child($dom->create_text_node('Trachtenberg')); // print a nicely formatted version of the DOM document as XML echo $dom->dump_mem(true); <?xml version="1.0"?> <book> <title cover="soft">PHP Cookbook</title> <author>Sklar</author> <author>Trachtenberg</author> </book>
Discussion
A single element is known as a node . Nodes can be of a dozen different types, but the three most popular are elements, attributes, and text. Given this:
<book cover="soft">PHP Cookbook</book>
PHP’s ...
Get PHP Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.