查看完整版本: PHP将将 XML 映射为 HTML的代码实例

Kenny 2007-8-2 13:29

PHP将将 XML 映射为 HTML的代码实例

             <p>以下范例将 <a href="http://www.phpchina.com/javascript:;" onClick="javascript:tagshow(event, 'XML');" target="_self"><u><strong>XML</strong></u></a> 文档中的标记符直接映射成 <a href="http://www.phpchina.com/javascript:;" onClick="javascript:tagshow(event, 'HTML');" target="_self"><u><strong>HTML</strong></u></a> 标记符。在“映射数组”中不存在的元素将被忽略。当然,该范例将只对一个特定的 XML 文档有效。 <DIV class=code><P>&lt;?php<BR>$file = "data.xml";<BR>$map_array = array(<BR>&nbsp;&nbsp; "BOLD"&nbsp;&nbsp;&nbsp; =&gt; "B",<BR>&nbsp;&nbsp; "EMPHASIS" =&gt; "I",<BR>&nbsp;&nbsp; "LITERAL"&nbsp; =&gt; "TT"<BR>);</P><P>function startElement($parser, $name, $attrs) {<BR>&nbsp;&nbsp; global $map_array;<BR>&nbsp;&nbsp; if ($htmltag == $map_array[$name]) {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print "&lt;$htmltag&gt;";<BR>&nbsp;&nbsp; }<BR>}</P><P>function endElement($parser, $name) {<BR>&nbsp;&nbsp; global $map_array;<BR>&nbsp;&nbsp; if ($htmltag == $map_array[$name]) {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print "&lt;/$htmltag&gt;";<BR>&nbsp;&nbsp; }<BR>}</P><P>function characterData($parser, $data) {<BR>&nbsp;&nbsp; print $data;<BR>}</P><P>$xml_parser = xml_parser_create();<BR>// 使用大小写折叠来保证我们能在元素数组中找到这些元素名称<BR>xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true);<BR>xml_set_element_handler($xml_parser, "startElement", "endElement");<BR>xml_set_character_data_handler($xml_parser, "characterData");<BR>if (!($fp = fopen($file, "r"))) {<BR>&nbsp;&nbsp; die("could not open XML input");<BR>}</P><P>while ($data = fread($fp, 4096)) {<BR>&nbsp;&nbsp; if (!xml_parse($xml_parser, $data, feof($fp))) {<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; die(sprintf("XML error: %s at line %d",<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; xml_error_string(xml_get_error_code($xml_parser)),<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; xml_get_current_line_number($xml_parser)));<BR>&nbsp;&nbsp; }<BR>}<BR>xml_parser_free($xml_parser);<BR>?&gt;&nbsp;</P>
页: [1]
查看完整版本: PHP将将 XML 映射为 HTML的代码实例
PageRank