正好昨天才做过类似的需求……几行代码就可以搞定。

如果你使用 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与数组互转

2007-12-18 12:29:37|  分类: Xml |举报 |字号 订阅

 

//如果乱码的话更改header函数

<?php //header('Content-type: text/html;charset=utf-8');
class xmlarray
{

private $xml = '';//用于读取xml的变量
    private $data;    //生成的xml
    private $dom_tree;//xml目录树
/**
   __construct仅用于读取xml
*/
    function __construct($xml="")
    {
   if(empty($xml))
   {
    return null;
   }
   //$this->xml = $xml;
   else
   {
             $this->loadxml($xml);
   }
    }
/**
     装载要处理的xml文档也可以在初始化时装载
*/
public function loadxml($filepath)
{  
      $handle = @fopen($filepath,"r");

while (!feof($handle)&&$handle)
   {
              $xml_data .= fgets($handle, 4096);
         }
   $this->xml=$xml_data;
}
/**
     处理xml文档
*/
    private function _struct_to_array($values, &$i)
    {
   $child = array();
   if (isset($values[$i]['value'])) array_push($child, $values[$i]['value']);

while ($i++ < count($values))
   {
    switch ($values[$i]['type'])
    {
     case 'cdata':
      array_push($child, $values[$i]['value']);
      break;

case 'complete':
      $name = $values[$i]['tag'];
      if(!empty($name))
      {
       $child[$name]= ($values[$i]['value'])?($values[$i]['value']):'';
       if(isset($values[$i]['attributes']))
       {
        $child[$name] = $values[$i]['attributes'];
       }
      }
      break;

case 'open':
      $name = $values[$i]['tag'];
      $size = isset($child[$name]) ? sizeof($child[$name]) : 0;
      $child[$name][$size] = $this->_struct_to_array($values, $i);
     break;

case 'close':
      return $child;
      break;
    }
   }
   return $child;
    }
/**
    处理xml文档,实际调用 _struct_to_array()处理
*/
    public function xml2array()
    {
        $xml    =& $this->xml;
        $values = array();
        $index = array();
        $array = array();
        $parser = xml_parser_create();
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
        xml_parse_into_struct($parser, $xml, $values, $index);

xml_parser_free($parser);
        $i = 0;
        $name = $values[$i]['tag'];
        $array[$name] = isset($values[$i]['attributes']) ? $values[$i]['attributes'] : '';
        $array[$name] = $this->_struct_to_array($values, $i);
        return $array;
    }

//以下为将数组转换成xml的代码 使用dom
        /**
     读取数组
         */
        public function array2xml($array){
            if(!is_array($array)){
                throw new Exception('array2xml requires an array', 1);
                unset($array);
            }
            if(!count($array)){
                throw new Exception('array is empty', 2);
                unset($array);
            }
           
            $this->data = new DOMDocument();         
            $this->dom_tree = $this->data->createElement('result');//默认要标签
            $this->data->appendChild($this->dom_tree);
            $this->recurse_node($array, $this->dom_tree);
        }
       
        /**
             处理数组为xml
         */
        private function recurse_node($data, $obj){
            $i = 0;
            foreach($data as $key=>$value){
                if(is_array($value)){
                    //recurse if neccisary
                    $sub_obj[$i] = $this->data->createElement($key);//创建标签
                    $obj->appendChild($sub_obj[$i]); //将标签加入到$obj标签下
                    $this->recurse_node($value, $sub_obj[$i]); //将值加入此标签下
                } elseif(is_object($value)) {
                    //no object support so just say what it is
                   
$sub_obj[$i] = $this->data->createElement($key, 'Object: "' .
$key . '" type: "' . get_class($value) . '"');
                    $obj->appendChild($sub_obj[$i]);
                } else {
                    //straight up data, no weirdness
                    $sub_obj[$i] = $this->data->createElement($key, $value);
      //如果是最后的节点,将节点名和内容创建
                    $obj->appendChild($sub_obj[$i]);
                }
                $i++;
            }
        }
       
        /**
       将数组保存成xml文件
         */
        public function saveXML($arraytoxml="")
   {
    if($arraytoxml=="")
    {
     $out = iconv("gbk","utf-8","请输入将要保存的文件名");
     echo "<script>alert('$out')</script>";
    }
    else
    {
                 return $this->data->save($arraytoxml);
    }
        }
}
?>

将数组转换成xml文件
<?php
   $test = array(
        'one'=>'number',
        'two'=> array(
            'c'=>1,
            'd'=>2,
            'e'=>3,
            'f'=>4
        ),
        'three'=>'alpha'
    );
   /*创建对象*/
   $xmlObj= new xmlarray();
   /*转换*/
   $xml = $xmlObj->array2xml($test);
   /*输出保存*/
   $xmlObj->saveXML("a.xml");
   ?>

将xml解析为数组输出
<?php
   /*创建对象*/
   $xmlObj    = new xmlarray();
   /*装载*/
   $xml = $xmlObj->loadxml("a.xml");
   /*转换*/
   $data=$xmlObj->xml2array();
   /*显示*/
   print_r($data);
?>

php xml 互相转换的更多相关文章

  1. 利用JAXB实现java实体类和xml互相转换

    1.应用场景 在使用WebService实现数据上传下载,数据查询时,可以利用JAXB实现java实体类和xml互相转换 2.Demo 2.1 student.java 实体类,包含list(set同 ...

  2. 将Xml字符串转换成(DataTable || DataSet || XML)对象

    今天用到一个功能:就是把从数据库读出来的内容转换成XML字符串流格式,并输出给一个功能函数.在写的过程,为方便以后的使用,我对这一功能进行分装.该类的具体格式如下:XmlConvert类命名空间:Ni ...

  3. SpringMVC关于json、xml自动转换的原理研究[附带源码分析 --转

    SpringMVC关于json.xml自动转换的原理研究[附带源码分析] 原文地址:http://www.cnblogs.com/fangjian0423/p/springMVC-xml-json-c ...

  4. json串转化成xml文件、xml文件转换成json串

    1.json串转化成xml文件 p=[{"name":"tom","age":30,"sex":"男" ...

  5. SpringMVC源码阅读:Json,Xml自动转换

    1.前言 SpringMVC是目前J2EE平台的主流Web框架,不熟悉的园友可以看SpringMVC源码阅读入门,它交代了SpringMVC的基础知识和源码阅读的技巧 本文将通过源码(基于Spring ...

  6. JAXB实现java对象与xml之间转换

    JAXB简介: 1.JAXB能够使用Jackson对JAXB注解的支持实现(jackson-module-jaxb-annotations),既方便生成XML,也方便生成JSON,这样一来可以更好的标 ...

  7. c#开发微信公众号——关于c#对象与xml的转换

    在成为微信公众号开发者以后,整个交互流程:用户->微信服务器->自己的服务器->返回微信服务器->用户: 举个例子:用户在微信公众号里面发了个“您好!”,微信服务器会以特定的x ...

  8. C# 实现DataTable、DataSet与XML互相转换

    /**//// <summary> /// 把DataSet.DataTable.DataView格式转换成XML字符串.XML文件 /// </summary> public ...

  9. Sql 把Xml字符串转换成一张表

    分享一个Sql技巧,把xml字符串转换成一个表格 DECLARE @IdHandel INT EXEC sp_xml_preparedocument @IdHandel OUTPUT, @Bar_Ip ...

  10. 在线好用的json转xml超级好用在线json与xml互相转换

    在线好用的json转xml超级好用在线json与xml互相转换 拿走不谢:http://www.yzcopen.com/json/jsonxmlformat

随机推荐

  1. HDU 2188 悼念512汶川大地震遇难同胞――选拔志愿者(巴什博奕)

    选拔志愿者 题意: 对于四川同胞遭受的灾难,全国人民纷纷伸出援助之手,几乎每个省市都派出了大量的救援人员,这其中包括抢险救灾的武警部队,治疗和防疫的医护人员,以及进行心理疏导的心理学专家.根据要求,我 ...

  2. KMP算法的Next数组详解 转

    这个写的很好,还有讲kmp,值得一看. http://www.cnblogs.com/tangzhengyue/p/4315393.html 转载请注明来源,并包含相关链接. 网上有很多讲解KMP算法 ...

  3. NeHe OpenGL教程 第十二课:显示列表

    转自[翻译]NeHe OpenGL 教程 前言 声明,此 NeHe OpenGL教程系列文章由51博客yarin翻译(2010-08-19),本博客为转载并稍加整理与修改.对NeHe的OpenGL管线 ...

  4. VMWare虚拟机下RedHat 9.0linux的网络设置

    VMWare虚拟机下安装的RedHat 9.0 linux有三种方式实现上网,桥接.nat.host-only.本来想用桥接方式的,可总是因为配置网络出现问题而不能上网,还把 sygate4.5(代理 ...

  5. C#2

    同名的两个类如果在不同的命名空间中,相互之间是不会混淆的. 一个名为TextHello的命名空间中创建一个名为Program的类,引用方法 TextHello.Program 我们常用的Console ...

  6. 程序进入 EXPORT App_Fault_ISR的原因及措施:

    最近再UCOSIII+LPC1768上移植modbus,在定时器初始化部分竟然跑飞进入 EXPORT  App_Fault_ISR,查资料.逛论坛.问大牛都没有解决,最后发现竟然是犹豫一个低级失误引起 ...

  7. java网络编程之TCP实例

    Dgram类 package Socket; import java.net.DatagramPacket; import java.net.InetAddress; public class Dgr ...

  8. spring controller中@Value取不到applicationContext.xml中加载配置文件的问题

    原因还未查证: http://sunjun041640.blog.163.com/blog/static/256268322014127113844746/ 在使用spring mvc时,实际上是两个 ...

  9. Jquery插件收藏

    1.带小图标的多级菜单导航 演示地址:http://js.itivy.com/memu/sample.html 下载地址:http://js.itivy.com/?p=100 效果图:  推荐一个自己 ...

  10. SQL锁表解决并发性

    在数据库开发过程中,不得不考虑并发性的问题,因为很有可能当别人正在更新表中记录时,你又从该表中读数据,那你读出来的数据有可能就不是你希望得到的数据.可以说有些数据同时只能有一个事物去更新,否则最终显示 ...