当前位置:首页 > PHP教程 > php应用 > 列表

PHP遍历解析XML成数组实现方法

发布:smiling 来源: PHP粉丝网  添加日期:2014-08-20 14:58:24 浏览: 评论:0 
  1. public function parsexml($menus){ 
  2.          $result = array(); 
  3.          foreach($menus as $menu){ 
  4.              $tmparr = array(); 
  5.   
  6.              //    处理空文本节点方式a 
  7.              if$menu->nodename !='#text'){ 
  8.   
  9.                  //    检索子元素时跳跃过文本节点  - 处理空文本节点方式b 
  10.                  for($i=1; $i<$menu->childnodes->length; $i+=2) { 
  11.                      $anode = $menu->childnodes->item($i); 
  12.   
  13.                      //    子元素遍历 
  14.                      $anode->childnodes->length > 1 ? $tmparr[$anode->nodename] = $this->parsexml( $anode->childnodes)  
  15.                      : $tmparr[$anode->nodename] = $anode->nodevalue; 
  16.                  } 
  17.                  array_push($result,$tmparr); 
  18.              } 
  19.          } 
  20.          return $result
  21.      } 
  22.           $doc = new domdocument(); 
  23.          $doc->load ( ‘a.xml’ ); 
  24.   
  25.          //    第一种,有空文本节点 
  26.          $menus = $doc->getelementsbytagname('sitemap')->item(0)->childnodes;   
  27.   
  28.           //    第二种,明确指定标签,序列无空文本节点。但子元素仍然有空节点 
  29.  //开源代码phpfensi.com 
  30.          $xpath = new domxpath($doc); 
  31.          $query = "/sitemap/child::a"
  32.   
  33.          $menus = $xpath->query($query); 

Tags: PHP遍历XML PHP解析XML

分享到: