PHP解析XML 元素结构范例

以下范例将 XML 文档中的标记符直接映射成 HTML
标记符。在“映射数组”中不存在的元素将被忽略。当然,该范例将只对一个特定的
XML 文档有效。 ?php$file = “data.xml”;$map_array = array( “BOLD” = “B”,
“EMPHASIS” = “I”, “LITERAL” = “TT”);function startElement($parser,
$name, $attrs) { global $map_array; if ($htmltag ==
$map_array[$name]) { print “$htmltag”; }}function endElement($parser,
$name) { global $map_array; if ($htmltag == $map_array[$name]) {
print “/$htmltag”; }}function characterData($parser, $data) { print
$data;}$xml_parser = xml_parser_create();//
使用大小写折叠来保证我们能在元素数组中找到这些元素名称xml_parser_set_option($xml_parser,
XML_OPTION_CASE_FOLDING,
true);xml_set_element_handler($xml_parser, “startElement”,
“endElement”);xml_set_character_data_handler($xml_parser,
“characterData”);if (!($fp = fopen($file, “r”))) { die(“could not open
XML input”);}while ($data = fread($fp, 4096)) { if
(!xml_parse($xml_parser, $data, feof($fp))) { die(sprintf(“XML error:
%s at line %d”, xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)));
}}xml_parser_free($xml_parser);?

该范例用缩进格式显示一个文档中起始元素的结构。 显示 XML
元素结构?php$file = “data.xml”;$depth = array();function
startElement($parser, $name, $attrs) { global $depth; for ($i = 0; $i
$depth[$parser]; $i ) { print ” “; } print “$name”; $depth[$parser]
;}function endElement($parser, $name) { global $depth;
$depth[$parser]–;}$xml_parser =
xml_parser_create();xml_set_element_handler($xml_parser,
“startElement”, “endElement”);if (!($fp = fopen($file, “r”))) {
die(“could not open XML input”);}while ($data = fread($fp, 4096)) { if
(澳门新葡亰网站注册,!xml_parse($xml_parser, $data, feof($fp))) { die(sprintf(“XML error:
%s at line %d”, xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)));
}}xml_parser_free($xml_parser);?