怎么在php项目中使用expat解析xml文件
这期内容当中小编将会给大家带来有关怎么在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文件了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注恰卡编程网行业资讯频道。
推荐阅读
-
Linux中如何安装和使用 PHP 开发环境
-
php字符串增加1如何实现
php字符串增加1如何实现这篇“php字符串增加1如何实现”文章的...
-
php如何判断字符串是否有中文
php如何判断字符串是否有中文本文小编为大家详细介绍“php如何判...
-
php如何实现字符串去掉头尾
php如何实现字符串去掉头尾这篇“php如何实现字符串去掉头尾”文...
-
php字符串的组成是什么
php字符串的组成是什么这篇文章主要讲解了“php字符串的组成是什...
-
php如何让Swoole/Pool进程池实现Redis持久连接
php如何让Swoole/Pool进程池实现Redis持久连接本篇...
-
php字符串长度不一致如何解决
php字符串长度不一致如何解决本篇内容主要讲解“php字符串长度不...
-
php时区不正确如何解决
php时区不正确如何解决本文小编为大家详细介绍“php时区不正确如...
-
php+fread()乱码如何解决
php+fread()乱码如何解决本篇内容介绍了“php+frea...
-
php explode报错如何解决
phpexplode报错如何解决这篇文章主要介绍“phpexp...