这期内容当中小编将会给大家带来有关怎么在php项目中使用expat解析xml文件,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
具体如下:

test.xml:
<?xmlversion="1.0"encoding="UTF-8"?>
<notes>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don'tforgetthemeeting!</body>
</note>
<note>
<to>George2</to>
<from>John2</from>
<heading>Reminder2</heading>
<body>Don'tforgetthemeeting!2</body>
</note>
<instances>
<instancest="192.168.234.121"/>
<instancest="192.168.234.28"/>
</instances>
</notes>
PHP文件:
<?php
//InitializetheXMLparser
$parser=xml_parser_create();
//Functiontouseatthestartofanelement
functionstart($parser,$element_name,$element_attrs)
{
switch($element_name){
case"NOTE":
echo"--Note--<br/>";
break;
case"TO":
echo"To:";
break;
case"FROM":
echo"From:";
break;
case"HEADING":
echo"Heading:";
break;
case"BODY":
echo"Message:";
}
}
//Functiontouseattheendofanelement
functionstop($parser,$element_name)
{
echo"<br/>";
}
//Functiontousewhenfindingcharacterdata
functionchar($parser,$data)
{
echo$data;
}
//Specifyelementhandler
xml_set_element_handler($parser,"start","stop");
//Specifydatahandler
xml_set_character_data_handler($parser,"char");
//OpenXMLfile
//$fp=fopen("test.xml","r");
//Readdata
//while($data=fread($fp,10)){
//xml_parse($parser,$data,feof($fp))ordie(sprintf("XMLError:%satline%d",xml_error_string(xml_get_error_code($parser)),xml_get_current_line_number($parser)));
//}
//fclose($fp);
$data=file_get_contents("test.xml");
xml_parse($parser,$data)ordie(sprintf("XMLError:%satline%d",xml_error_string(xml_get_error_code($parser)),xml_get_current_line_number($parser)));
//FreetheXMLparser
xml_parser_free($parser);
?>
运行结果:
-- Note --To: GeorgeFrom: JohnHeading: ReminderMessage: Don't forget the meeting!
-- Note --To: George2From: John2Heading: Reminder2Message: Don't forget the meeting!2
上述就是小编为大家分享的怎么在php项目中使用expat解析xml文件了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注恰卡编程网行业资讯频道。