PHP 8.3.0 RC 6 available for testing

XML 标签映射示例

示例 #1 将 XML 映射为 HTML

此示例直接地将 XML 标签映射为 HTML 标签。在“map_array”中未找到的元素将被忽略。当然,此示例只针对特定的 XML 文档类型起作用。

<?php
$file
= "data.xml";
$map_array = array(
"BOLD" => "B",
"EMPHASIS" => "I",
"LITERAL" => "TT"
);

function
startElement($parser, $name, $attrs)
{
global
$map_array;
if (isset(
$map_array[$name])) {
echo
"<$map_array[$name]>";
}
}

function
endElement($parser, $name)
{
global
$map_array;
if (isset(
$map_array[$name])) {
echo
"</$map_array[$name]>";
}
}

function
characterData($parser, $data)
{
echo
$data;
}

$xml_parser = xml_parser_create();
// use case-folding so we are sure to find the tag in $map_array
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);
?>

add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top