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

php中SimpleXMLElement 对象转换为数组

发布:smiling 来源: PHP粉丝网  添加日期:2014-08-20 14:01:23 浏览: 评论:0 

PHP 提供了 simplexml_load_string 方法用来解析 XML 格式的字符串,并返回 SimpleXMLElement 对象,不过一般数组是更为适用的,所以也会有转换为普通数组的需求,这个方法测试完全奏效,支持 SimpleXMLElement 对象多层嵌套的情况.

提供两个参数,第一个参数为 SimpleXMLElement 对象,第二个参数为布尔值,控制最终返回值是否包含根节点,代码如下:

  1. function xmlToArr ($xml$root = true) { 
  2.  
  3.   if (!$xml->children()) { 
  4.    return (string) $xml
  5.   } 
  6.   $array = array(); 
  7.   foreach ($xml->children() as $element => $node) { 
  8.    $totalElement = count($xml->{$element}); 
  9.    if (!isset($array[$element])) { 
  10.     $array[$element] = ""
  11.    } 
  12.    // Has attributes 
  13.    if ($attributes = $node->attributes()) { 
  14.     $data = array
  15.      'attributes' => array(), 
  16.      'value' => (count($node) > 0) ? $this->__xmlToArr($node, false) 
  17.  
  18. : (string) $node 
  19.     ); 
  20.     foreach ($attributes as $attr => $value) { 
  21.      $data['attributes'][$attr] = (string) $value
  22.     } 
  23.     if ($totalElement > 1) { 
  24.      $array[$element][] = $data
  25.     } else { 
  26.      $array[$element] = $data
  27.     } 
  28.    // Just a value 
  29.    } else { 
  30.     if ($totalElement > 1) { 
  31.      $array[$element][] = $this->__xmlToArr($node, false); 
  32.     } else { 
  33.      $array[$element] = $this->__xmlToArr($node, false); 
  34.     } 
  35.    } 
  36.   }//开源代码phpfensi.com 
  37.   if ($root) { 
  38.    return array($xml->getName() => $array); 
  39.   } else { 
  40.    return $array
  41.   } 
  42.  
  43.  } 

Tags: SimpleXMLElement 对象转换为数组

分享到: