20.4 Mapping XML Tags


You want to convert XML tags into either a singular HTML tag or a set of HTML tags.

Technique

Use an associative array to trigger start elements and end elements:

 html-test.xml: <faqs>     <faq id="1">         <title>FAQ 1</title>         <code>            idx = p - str;         </code>         <text>             The above is a piece of code from rand.c in             <important>ext/standard</important> in the PHP distribution.         </text>     </faq> </faqs> html-test.php: <?php $start = array('title' => '<h2>',                'text' => '<font face="arial, helvetica" size="2">',                'code' => '<pre>',                'important' => '<b>'); $end = array('title' => '</h2>',              'text' => '</font>',              'code' => '</pre>',              'important' => '</b>'); function start_html ($parser, $element_name, $element_attrs) {     global $start;      echo $start[strtolower($element_name)]; } function end_html ($parser, $element_name) {     global $end;     echo $end[strtolower($element_name)]; } function character_data ($parser, $data) {     echo $data; } $parser = xml_parser_create(); xml_set_element_handler ($parser, "start_html", "end_html"); xml_set_character_data_handler ($parser, "character_data"); $fp = fopen ("html-test.xml", "r") or die("Cannot open file"); while ($data = fread($fp, 4096)) {     xml_parse($parser, $data, feof($fp)) or         die(sprintf('XML Error: %s at line %d',                     xml_error_string(xml_get_error_code($parser)),                     xml_get_current_line_number($parser))); } fclose($fp); xml_parser_free($parser); ?> 

Comments

In the example, we maintain a global associative array that maps XML elements to their HTML equivalents. Then we parse the XML elements, and replace each recognized tag with the appropriate formatting for that tag. We also maintain an array of end tags for each array because, start tags and end tags can differ by much more than simply a /.

PHP is good for parsing and displaying XML documents on-the-fly. But if you do not need to parse your documents on-the-fly , you are better off using something like XML and DSSSL and then parsing your documents with Jade ”they allow for much more power than the techniques described here. By the way, PHP documentation is written using XML and DSSSL as the format (Jade is used to generate the different types of files, such as HTML or PDF).



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