我注意到在下面的範例中,以及我在這個網站上看到的所有用於在 HTML 中檢視 XML 的範例中,自閉合標籤(例如 <br />)的外觀沒有保留。解析器無法區分 <tag /> 和 <tag></tag>,如果您的開始和結束元素函數與這些範例類似,則兩個實例都會輸出個別的開始和結束標籤。我需要保留自閉合標籤,並且我花了一些時間才找出這個解決方法。希望這對某些人有幫助...
開始標籤會保持開啟狀態,然後由其第一個子項、下一個開始標籤或其結束標籤完成。結束標籤將會根據已解析資料中開始和結束標籤之間的位元組數,以 " />" 或 </tag> 完成。
<?php
$data=<<<DATA
<normal_tag>
<self_close_tag />
data
<normal_tag>data
<self_close_tag attr="value" />
</normal_tag>
data
<normal_tag></normal_tag>
</normal_tag>
DATA;
function startElement($parser, $name, $attrs)
{
xml_set_character_data_handler($parser, "characterData");
global $first_child, $start_byte;
if($first_child) echo "><br />";
$first_child=true;
$start_byte=xml_get_current_byte_index ($parser);
if(count($attrs)>=1){
foreach($attrs as $x=>$y){
$attr_string .= " $x=\"$y\"";
}
}
echo htmlentities("<{$name}{$attr_string}"); }
function endElement($parser, $name)
{
global $first_child, $start_byte;
$byte=xml_get_current_byte_index ($parser);
if($byte-$start_byte>2){ if($first_child) echo "><br />";
echo htmlentities("</{$name}>")."<br />"; }else
echo " /><br />"; $first_child=false;
}
function characterData($parser, $data)
{
global $first_child;
if($first_child) echo "><br />";
if($data=trim($data))
echo "<font color='blue'>$data</font><br />";
$first_child=false;
}
function ParseData($data)
{
$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_parser_set_option($xml_parser,XML_OPTION_CASE_FOLDING,0);
if(is_file($data))
{
if (!($fp = fopen($file, "r"))) {
die("無法開啟 XML 輸入");
}
while ($data = fread($fp, 4096)) {
if (!xml_parse($xml_parser, $data, feof($fp))) {
$error=xml_error_string(xml_get_error_code($xml_parser));
$line=xml_get_current_line_number($xml_parser);
die(sprintf("XML 錯誤:%s,在第 %d 行",$error,$line));
}
}
}else{
if (!xml_parse($xml_parser, $data, 1)) {
$error=xml_error_string(xml_get_error_code($xml_parser));
$line=xml_get_current_line_number($xml_parser);
die(sprintf("XML 錯誤:%s,在第 %d 行",$error,$line));
}
}
xml_parser_free($xml_parser);
}
ParseData($data);
?>