Hack54.Create XML the Right Way


Hack 54. Create XML the Right Way

Use the XML DOM to create XML without errors.

Creating XML from your PHP web application is easy to get wrong. You can screw up the encoding so that special characters are not formatted properly, and you can miss start or end tags. Both of these problems, which are common in even simple PHP applications, will result in invalid XML and will keep the XML from being read properly by other XML consumers. Almost all of the problems result from working with XML as streams of characters instead of using an XML API such as DOM.

This hack will show you how to create XML DOMs in memory and then export them as text. This method of creating XML avoids all of these encoding and formatting issues, so your XML will be well-formed every time.

Figure 6-6 shows the in-memory XML tree that we will create in this hack. Each element is an object. The base of the system is DOMDocument, which points to the root node of the tree. From there, each DOMElement node can contain one or more child nodes and attribute nodes.

Figure 6-6. The in-memory XML tree


6.5.1. The Code

Save the code in Example 6-6 as xmldom.php.

Example 6-6. Sample code that builds XML the right way
 <?php  $books = array( array ( id => 1, author => "Jack Herrington", name => "Code Generation in Action"   ), array ( id => 2, author => "Jack Herrington", name => "Podcasting Hacks"   ), array ( id => 3, author => "Jack Herrington", name => "PHP Hacks" ) ); $dom = new DomDocument();  $dom->formatOutput = true; $root = $dom->createElement( "books" ); $dom->appendChild( $root ); foreach( $books as $book ) { $bn = $dom->createElement( "book" ); $bn->setAttribute( 'id', $book['id'] ); $author = $dom->createElement( "author" ); $author->appendChild( $dom->createTextNode( $book['author'] ) ); $bn->appendChild( $author ); $name = $dom->createElement( "name" ); $name->appendChild( $dom->createTextNode( $book['name'] ) ); $bn->appendChild( $name ); $root->appendChild( $bn );  } header( "Content-type: text/xml" ); echo $dom->saveXML(); ?> 

6.5.2. Running the Hack

Upload this file to your server and surf to the xmldom.php page. You should see something like Figure 6-7.

This is nicely formatted and well-formed XML, and I didn't have to manually output a single tag name or attribute value. Instead, the DOM handles object creation and ties the objects together via the appendChild() method. Finally, saveXML() is used to export the XML as text. This is the easy and object-oriented way to create XML that is valid every time.

6.5.3. See Also

  • "Design Better SQL Schemas" [Hack #34]

  • "Create Bulletproof Database Access" [Hack #35]

Figure 6-7. The book XML shown in the Firefox browser




PHP Hacks
PHP Hacks: Tips & Tools For Creating Dynamic Websites
ISBN: 0596101392
EAN: 2147483647
Year: 2006
Pages: 163

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net