TechniqueUse 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); ?> CommentsIn 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). |