Recipe 12.1. Generating XML as a String


12.1.1. Problem

You want to generate XML. For instance, you want to provide an XML version of your data for another program to parse.

12.1.2. Solution

Loop through your data and print it out surrounded by the correct XML tags:

<?php header('Content-Type: text/xml'); print '<?xml version="1.0"?>' . "\n"; print "<shows>\n"; $shows = array(array('name'     => 'Simpsons',                      'channel'  => 'FOX',                      'start'    => '8:00 PM',                      'duration' => '30'),                array('name'     => 'Law & Order',                      'channel'  => 'NBC',                      'start'    => '8:00 PM',                      'duration' => '60')); foreach ($shows as $show) {     print "    <show>\n";     foreach($show as $tag => $data) {         print "        <$tag>" . htmlspecialchars($data) . "</$tag>\n";     }     print "    </show>\n"; } print "</shows>\n"; ?>

12.1.3. Discussion

Printing out XML manually mostly involves lots of foreach loops as you iterate through arrays. However, there are a few tricky details. First, you need to call header( ) to set the correct Content-Type header for the document. Since you're sending XML instead of HTML, it should be text/xml.

Next, depending on your settings for the short_open_tag configuration directive, trying to print the XML declaration may accidentally turn on PHP processing. Since the <? of <?xml version="1.0"?> is the short PHP open tag, to print the declaration to the browser you need to either disable the directive or print the line from within PHP. We do the latter in the Solution.

Last, entities must be escaped. For example, the & in the show Law & Order needs to be &amp;. Call htmlspecialchars( ) to escape your data.

The output from the example in the Solution is shown in Example 12-1.

Tonight's TV listings

<?xml version="1.0"?> <shows>     <show>         <name>Simpsons</name>         <channel>FOX</channel>         <start>8:00 PM</start>         <duration>30</duration>     </show>     <show>         <name>Law &amp; Order</name>         <channel>NBC</channel>         <start>8:00 PM</start>         <duration>60</duration>     </show> </shows>

12.1.4. See Also

Recipe 12.2 for generating XML using DOM; documentation on htmlspecialchars( ) at http://www.php.net/htmlspecialchars.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

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