20.10 Building an XML Document


You want to build an XML document with PHP, but using multiple print statements just doesn't seem elegant or efficient.

Technique

Use the DOM-XML functions to help you build an XML document:

 <?php $doc = new_xmldoc('1.0'); $root = $doc->add_root('sites'); $site = $root->new_child('site', ''); $site->new_child('title', 'PHP.net'); $site->new_child('url', 'http://www.php.net'); $site->new_child('description', 'The homepage of PHP'); $site->new_child('keywords',                  'MySQL, PHP, Documentation, downloads, articles, books'); $fp = @fopen('tst.xml', 'w'); if (!$fp) {     die('Error couldn't open XML file, tst.xml'); } fwrite($fp, $doc->dumpmem()); fclose($fp); ?> 

Description

Here we use a subset of the DOM-XML functions to create the document we parsed in the previous recipe. Using the DOM XML functions makes building XML documents much easier because the functions enable us to view the Web page as a tree structure. Therefore, instead of building the document with multiple, repetitive print statements, we can build the document as we would view it.

This can also be a powerful set of constructs when used in conjunction with text files. We can parse the plain text files into internal data structures, and then use the DOM-XML functions to output them in XML. Consider the following file:

 Name  Address  Phone  Email 

With the next script, we parse these entries into the following XML entries:

 <addressbook>     <person>         <name>Name</name>         <address>Address</address>         <phone>Phone</phone>         <email>Email</email>     </person> </addressbook> 

Here is the script:

 <?php $infile  = isset($argv[1]) ? $argv[1] : 'php://stdin'; $outfile = isset($argv[2]) ? $argv[2] : 'php://stdout'; $doc = new_xmldoc('1.0'); if (!$doc) {     die("Couldn't create new XML document"); } $root = $doc->add_root('addressbook'); if (!$root) {     die("Couldn't add root"); } $infp = @fopen($infile, 'r'); if (!$infp) {     die("Couldn't open $infile\n"); }      while ($line = @fgets($infp, 1024)) {     $data = explode('', $line);     $person = $root->new_child('person', '');     $person->new_child('name', $data[0]);     $person->new_child('address', $data[1]);     $person->new_child('phone', $data[2]);     $person->new_child('email', $data[3]); } @fclose($infp); $outfp = @fopen($outfile, 'w'); if (!$outfp) {     die("Couldn't open $outfile\n"); } @fwrite($outfp, $doc->dumpmem()); @fclose($fp); ?> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

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