萬盛學電腦網

 萬盛學電腦網 >> 網頁制作 >> 腳本Html教程 >> PHP將XML映射為HTML的代碼實例

PHP將XML映射為HTML的代碼實例

 以下范例將 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);
?>

copyright © 萬盛學電腦網 all rights reserved