我用php解析xml,php和xml代码如下:
php:
<?php
$file = "data.xml";
$ename = "";
function startElement($parser, $name, $attrs) {
global $ename;
$ename = $name;
}
function endElement($parser, $name) {
global $ename;
$ename = "";
}
function characterData($parser, $data)
{
global $ename;
$data=iconv("utf-8","gb2312",trim($data))."\n";
switch($ename)
{
case "Name":
echo $data;
break;
default: break;
}
}
$xml_parser = xml_parser_create("UTF-8");
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, false);
if (!($fp = fopen($file, "r"))) {
die("could not open XML input");
}
while ($data = fread($fp, 4096)) {
//echo("hihi");
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);
?>
data.xml
<?xml version="1.0" encoding="UTF-8"?>
<root>
<person>
<Name>NameIsHarry</Name>
<age>20</age>
<sex>male</sex>
</person>
<person>
<Name>NameIs测试</Name>
<age>20</age>
<sex>female</sex>
</person>
<person>
<Name>NameIs继续</Name>
<age>18</age>
<sex>male</sex>
</person>
</root>
我预想的输出结果应该是这样的
NameIsHarry
NameIs测试
NameIs继续
可实际上确是这样
NameIsHarry
NameIs
测试
NameIs
继续
这是为什么啊?第一条全是英文没问题,第二条英文+中文却调用了两次characterData函数,这让我好郁闷啊,请问高手这是为什么啊,有什么办法解决么?