[php]php的xml文件读取XMLReader源代码范例
[php]php的xml文件读取XMLReader源代码范例
[php]php的xml文件读取XMLReader,[php]php的xml文件读取XMLReader源代码范例
- <?php
- /**
- $xmlString = '<xml>
- <persons count="10">
- <person username="username1" age="20">this is username1 description</person>
- <person username="username2" age="20">this is username2 description</person>
- </persons>
- </xml>';
- $mXmlTest = new XmlTest();
- $dataList = $mXmlTest->parseXmlStr($xmlString);
- print_r($dataList);
- $xmlFile = './test.xml';
- $dataList = $mXmlTest->parseXmlFile($xmlFile);
- print_r($dataList);
- */
- class XmlTest{
- // <xml>
- // <persons count="10">
- // <person username="username1" age="20">this is username1 description</person>
- // <person username="username2" age="20">this is username2 description</person>
- // </persons>
- // </xml>
- /**
- * 解析返回的XML文档
- */
- public function parseXmlFile($xmlFile){
- $reader = new \XMLReader();
- $reader->open($xmlFile, 'UTF-8');
- $nodeName = '';
- $dataList = array();
- $data = array();
- while ($reader->read()){
- if($reader->nodeType == \XMLReader::ELEMENT){
- $nodeName = $reader->name;
- if($nodeName=='persons'){
- $count = $reader->getAttribute('count');
- if(!($count>0)){
- break;
- }
- }
- elseif($nodeName=='person'){
- $data = array(
- 'username'=>$reader->getAttribute('username'),
- 'age'=>$reader->getAttribute('age'),
- );
- }
- }
- if($reader->nodeType == \XMLReader::TEXT && !empty($nodeName)){
- if($nodeName=='person'){
- $data['description'] = strtolower($reader->value);
- $dataList[] = $data;
- }
- }
- }
- $reader->close();
- return $dataList;
- }
- /**
- * 解析返回的XML文档
- */
- public function parseXmlStr($xmlString){
- $reader = new \XMLReader();
- $reader->xml($xmlString,'UTF-8');
- $nodeName = '';
- $dataList = array();
- $data = array();
- while ($reader->read()){
- if($reader->nodeType == \XMLReader::ELEMENT){
- $nodeName = $reader->name;
- if($nodeName=='persons'){
- $count = $reader->getAttribute('count');
- if(!($count>0)){
- break;
- }
- }
- elseif($nodeName=='person'){
- $data = array(
- 'username'=>$reader->getAttribute('username'),
- 'age'=>$reader->getAttribute('age'),
- );
- }
- }
- if($reader->nodeType == \XMLReader::TEXT && !empty($nodeName)){
- if($nodeName=='person'){
- $data['description'] = strtolower($reader->value);
- $dataList[] = $data;
- }
- }
- }
- return $dataList;
- }
- }
来源:http://www.cnblogs.com/xiaoyaogege/p/6212161.html
热门文章推荐
- [php]优酷真实视频地址解析算法
- [Dz]discuz手机版支持视频播放的方法
- [PHP]php加密js解密的方法实例
- [php]用PHP打印出前一天的时间格式
- [PHP]mpeg,mp3,avi的ffmpeg的php转换类
- [php]php中3DES加密一个非常有用的3des加密
- [PHP]php.ini修改上传文件的大小限制处理方法
- [php]用过的最好用的php分页类源代码
请稍候...