首页 > 代码库 > php xml 文件读取 XMLReader
php xml 文件读取 XMLReader
php xml 文件读取
<?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; } }
php xml 文件读取 XMLReader
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。