php将xml转成数组的函数|PHP将XML转成数组的函数实例

更新时间:2020-09-30    来源:php函数    手机版     字体:

【www.bbyears.com--php函数】

例子

现在有一个uncletoo.xml的配置文件,格式如下:

Step 1: XML File



   
        ben
        A
   

   
        h2o
        K
   


        h2o
        K
   


1、读XML文件内容,并保存到字符串变量中

下面我们使用PHP自带的file_get_contents()函数将文件内容读取到一个字符串变量中:

$xmlfile = file_get_contents($path);

此时$xmlfile变量的值如下:

2、将字符串转换为对象

这一步我们将使用simplexml_load_string()函数,将上一步得到的字符串转换为对象(Object):

$ob= simplexml_load_string($xmlfile);

此时$ob的值如下:


3、将对象转换为JSON

上一步转换成对象后,现在,我们要将对象转换成JSON格式字符串:

$json  = json_encode($ob);

此时$json变量的值如下:


4、解析JSON字符串

这也是最后一步了,我们需要将JSON格式的字符串转换为我们需要的数组:

$configData = json_decode($json, true);

现在$configData里存储的数据就是我么最后要得到的数组,如下:


完整转换代码:

 代码如下


$xmlfile = file_get_contents($path);
$ob= simplexml_load_string($xmlfile);
$json  = json_encode($ob);
$configData = json_decode($json, true);
?>

下面为网上整理的xml转换数组函数


例子一,将XML转成数组

 代码如下

如果你使用 curl 获取的 xml data
$xml = simplexml_load_string($data);
$data["tk"] = json_decode(json_encode($xml),TRUE);
如果是直接获取 URL 数据的话
$xml = simplexml_load_file($data);
$data["tk"] = json_decode(json_encode($xml),TRUE);
先把 simplexml 对象转换成 json,再将 json 转换成数组。

例子二,通过遍历

 代码如下

// Xml 转 数组, 包括根键
function xml_to_array( $xml )
{
$reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
if(preg_match_all($reg, $xml, $matches))
{
$count = count($matches[0]);
for($i = 0; $i < $count; $i++)
{
$subxml= $matches[2][$i];
$key = $matches[1][$i];
if(preg_match( $reg, $subxml ))
{
$arr[$key] = xml_to_array( $subxml );
}else{
$arr[$key] = $subxml;
}
}
}
return $arr;
}
// Xml 转 数组, 不包括根键
function xmltoarray( $xml )
{
$arr = xml_to_array($xml);
$key = array_keys($arr);
return $arr[$key[0]];
}

例子三

 代码如下

function simplexml_obj2array($obj){
      if ($obj instanceof SimpleXMLElement) {
       $obj = (array)$obj;
      }
    
      if (is_array($obj)) {
       $result = $keys = array();
       foreach( $obj as $key=>$value)
       {
        isset($keys[$key]) ? ($keys[$key] += 1) : ($keys[$key] = 1);
    
        if( $keys[$key] == 1 )
        {
         $result[$key] = simplexml_obj2array($value);
        }
        elseif( $keys[$key] == 2 )
        {
         $result[$key] = array($result[$key], simplexml_obj2array($value));
        }
        else if( $keys[$key] > 2 )
        {
         $result[$key][] = simplexml_obj2array($value);
        }
       }
       return $result;
      } else {
       return $obj;
      }
 }
$xml=simplexml_load_file("D:/ www.111cn.net /lib/books.xml");
 
$rss = simplexml_obj2array($xml);

本文来源:http://www.bbyears.com/jiaocheng/101919.html