-
-
/**XML file analysis class - * Date: 2013-02-01
- * Author: fdipzone
- * Ver: 1.0
- * Edition bbs.it-home.org
- * func:
- * loadXmlFile($xmlfile) reads xml file and outputs Array
- * loadXmlString($xmlstring) reads xmlstring and outputs Array
- */
-
- class XMLParser{
- /**Read xml file
- * @param String $xmlfile
- * @return Array
- */
- public function loadXmlFile($xmlfile){
- // get xmlfile content
- $xmlstring = file_exists($xmlfile)? file_get_contents($xmlfile) : '';
-
- // parser xml
- list($flag, $data) = $this->parser($xmlstring);
- return $this->response($flag, $data);
- }
-
-
- /**读取xmlstring
- * @param String $xmlstring
- * @return Array
- */
- public function loadXmlString($xmlstring){
- // parser xml
- list($flag, $data) = $this->parser($xmlstring);
-
- return $this->response($flag, $data);
- }
-
- /**Interpret xml content
- * @param String $xmlstring
- * @return Array
- */
- private function parser($xmlstring){
- $flag = false;
- $data = array();
-
- // check xml format
- if($this->checkXmlFormat($xmlstring)){
- $flag = true;
-
- // xml to object
- $data = simpleXML_load_string($xmlstring, 'SimpleXMLElement', LIBXML_NOCDATA);
-
- // object to array
- $this->objectToArray($data);
- }
- return array($flag, $data);
- }
-
- /**Check whether the xml format is correct
- * @param String $xmlstring
- * @return boolean
- */
- private function checkXmlFormat($xmlstring){
- if($xmlstring==''){
- return false;
- }
-
- $xml_parser_obj = xml_parser_create();
-
- if(xml_parse_into_struct($xml_parser_obj, $xmlstring, $vals, $indexs)===1){ // 1:success 0:fail
- return true;
- }else{
- return false;
- }
- }
/**object 转 Array
- * @param object $object
- * @return Array
- */
- private function objectToArray(&$object){
- $object = (array)$object;
- foreach($object as $key => $value){
- if($value==''){
- $object[$key] = "";
- }else{
- if(is_object($value) || is_array($value)){
- $this->objectToArray($value);
- $object[$key] = $value;
- }
- }
- }
- }
/**Output returns
- * @param boolean $flag true:false
- * @param Array $data converted data
- * @return Array
- */
- private function response($flag=false, $data=array()){
- return array($flag, $data);
- }
- }
- ?>
-
复制代码
2,演示示例
-
- require "XMLParser.class.php";
-
- $xmlfile = 'file.xml';
- $xmlstring = '
-
- 1000
-
- 100
- fdipzone
- 1
- 28
-
- ';
-
- echo '
'; </li>
<li> </li>
<li>$xml_parser = new XMLParser(); </li>
<li>echo "response xmlfilern"; </li>
<li>list($flag, $xmldata) = $xml_parser->loadXmlFile($xmlfile); </li>
<li>if($flag){ </li>
<li> print_r($xmldata); </li>
<li>} </li>
<li> </li>
<li>echo "response xmlstringrn"; </li>
<li>list($flag, $xmldata) = $xml_parser->loadXmlString($xmlstring); </li>
<li>if($flag){ </li>
<li> print_r($xmldata); </li>
<li>} </li>
<li> </li>
<li>echo ' ';
- ?>
复制代码
附,PHP XML预定义常量: http://bbs.it-home.org/shouce/php5/libxml.constants.html
|