一聚教程网:一个值得你收藏的教程网站

热门教程

php中SimpleXMLElement 对象转换为数组

时间:2022-06-24 20:51:05 编辑:袖梨 来源:一聚教程网

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

 代码如下 复制代码

function xmlToArr ($xml, $root = true) {

  if (!$xml->children()) {
   return (string) $xml;
  }
  $array = array();
  foreach ($xml->children() as $element => $node) {
   $totalElement = count($xml->{$element});
   if (!isset($array[$element])) {
    $array[$element] = "";
   }
   // Has attributes
   if ($attributes = $node->attributes()) {
    $data = array(
     'attributes' => array(),
     'value' => (count($node) > 0) ? $this->__xmlToArr($node, false)

: (string) $node
    );
    foreach ($attributes as $attr => $value) {
     $data['attributes'][$attr] = (string) $value;
    }
    if ($totalElement > 1) {
     $array[$element][] = $data;
    } else {
     $array[$element] = $data;
    }
   // Just a value
   } else {
    if ($totalElement > 1) {
     $array[$element][] = $this->__xmlToArr($node, false);
    } else {
     $array[$element] = $this->__xmlToArr($node, false);
    }
   }
  }
  if ($root) {
   return array($xml->getName() => $array);
  } else {
   return $array;
  }

 }

热门栏目