php之XML转数组函数的详解


Posted in PHP onJune 07, 2013

如下所示:

<?
/** 
* xml2array() will convert the given XML text to an array in the XML structure. 
* Link: http://www.bin-co.com/php/scripts/xml2array/ 
* Arguments : $contents - The XML text 
*                 $get_attributes - 1 or 0. If this is 1 the function will get the attributes as well as the tag values - this results in a different array structure in the return value. 
*                 $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance. 
* Return: The parsed XML in an array form. Use print_r() to see the resulting array structure. 
* Examples: $array =   xml2array(file_get_contents('feed.xml')); 
*               $array =   xml2array(file_get_contents('feed.xml', 1, 'attribute')); 
*/ 
function xml2array($contents, $get_attributes=1, $priority = 'tag') { 
     if(!$contents) return array(); 
     if(!function_exists('xml_parser_create')) { 
        //print "'xml_parser_create()' function not found!"; 
        return array(); 
     } 
    //Get the XML parser of PHP - PHP must have this module for the parser to work 
    $parser = xml_parser_create(''); 
    xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); # http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss 
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); 
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1); 
    xml_parse_into_struct($parser, trim($contents), $xml_values); 
    xml_parser_free($parser); 
     if(!$xml_values) return;//Hmm... 
     //Initializations 
    $xml_array = array(); 
    $parents = array(); 
    $opened_tags = array(); 
    $arr = array(); 
    $current = &$xml_array; //Refference 
     //Go through the tags. 
    $repeated_tag_index = array();//Multiple tags with same name will be turned into an array 
    foreach($xml_values as $data) { 
         unset($attributes,$value);//Remove existing values, or there will be trouble 
         //This command will extract these variables into the foreach scope 
         // tag(string), type(string), level(int), attributes(array). 
        extract($data);//We could use the array by itself, but this cooler. 
        $result = array(); 
        $attributes_data = array();          if(isset($value)) { 
             if($priority == 'tag') $result = $value; 
             else $result['value'] = $value; //Put the value in a assoc array if we are in the 'Attribute' mode 
        } 
        //Set the attributes too. 
        if(isset($attributes) and $get_attributes) { 
             foreach($attributes as $attr => $val) { 
                 if($priority == 'tag') $attributes_data[$attr] = $val; 
                 else $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr' 
            } 
         } 
        //See tag status and do the needed. 
        if($type == "open") {//The starting of the tag '<tag>' 
            $parent[$level-1] = &$current; 
             if(!is_array($current) or (!in_array($tag, array_keys($current)))) { //Insert New tag 
                $current[$tag] = $result; 
                 if($attributes_data) $current[$tag. '_attr'] = $attributes_data; 
                $repeated_tag_index[$tag.'_'.$level] = 1; 
                $current = &$current[$tag]; 
             } else { //There was another element with the same tag name 
                if(isset($current[$tag][0])) {//If there is a 0th element it is already an array 
                    $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result; 
                    $repeated_tag_index[$tag.'_'.$level]++; 
                 } else {//This section will make the value an array if multiple tags with the same name appear together 
                    $current[$tag] = array($current[$tag],$result);//This will combine the existing item and the new item together to make an array 
                    $repeated_tag_index[$tag.'_'.$level] = 2; 
                     if(isset($current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well 
                        $current[$tag]['0_attr'] = $current[$tag.'_attr']; 
                         unset($current[$tag.'_attr']); 
                     } 
                 } 
                $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1; 
                $current = &$current[$tag][$last_item_index]; 
             } 
         } elseif($type == "complete") { //Tags that ends in 1 line '<tag />' 
             //See if the key is already taken. 
            if(!isset($current[$tag])) { //New Key 
                $current[$tag] = $result; 
                $repeated_tag_index[$tag.'_'.$level] = 1; 
                 if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data; 
             } else { //If taken, put all things inside a list(array) 
                if(isset($current[$tag][0]) and is_array($current[$tag])) {//If it is already an array... 
                     // ...push the new element into that array. 
                    $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result; 
                     if($priority == 'tag' and $get_attributes and $attributes_data) { 
                        $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data; 
                     } 
                    $repeated_tag_index[$tag.'_'.$level]++; 
                 } else { //If it is not an array... 
                    $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value 
                    $repeated_tag_index[$tag.'_'.$level] = 1; 
                     if($priority == 'tag' and $get_attributes) { 
                         if(isset($current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well 
                            $current[$tag]['0_attr'] = $current[$tag.'_attr']; 
                             unset($current[$tag.'_attr']); 
                         } 
                         if($attributes_data) { 
                            $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data; 
                         } 
                     } 
                    $repeated_tag_index[$tag.'_'.$level]++; //0 and 1 index is already taken 
                } 
             } 
         } elseif($type == 'close') { //End of tag '</tag>' 
            $current = &$parent[$level-1]; 
         } 
     } 
     return($xml_array); 
} 
?>

函数描述及例子:
$arr = xml2array(file_get_contents("tools.xml"),1,'attribute');

PHP 相关文章推荐
中国站长站 For Dede4.0 采集规则
May 27 PHP
php Ajax乱码
Apr 09 PHP
php的正则处理函数总结分析
Jun 20 PHP
用PHP读取RSS feed的代码
Aug 01 PHP
连接到txt文本的超链接,不直接打开而是点击后下载的处理方法
Jul 01 PHP
php面向对象全攻略 (一) 面向对象基础知识
Sep 30 PHP
解析PHP自带的进位制之间的转换函数
Jun 08 PHP
IIS6.0 开启Gzip方法及PHP Gzip函数分享
Jun 08 PHP
php生成RSS订阅的方法
Feb 13 PHP
基于PHP技术开发客服工单系统
Jan 06 PHP
thinkPHP自动验证、自动添加及表单错误问题分析
Oct 17 PHP
Django中的cookie与session操作实例代码
Aug 17 PHP
利用php绘制饼状图的实现代码
Jun 07 #PHP
PHP自定义大小验证码的方法详解
Jun 07 #PHP
如何用php生成扭曲及旋转的验证码图片
Jun 07 #PHP
利用php获取服务器时间的实现代码
Jun 07 #PHP
探讨PHP中OO之静态关键字以及类常量的详解
Jun 07 #PHP
PHP5常用函数列表(分享)
Jun 07 #PHP
深入理解php的MySQL连接类
Jun 07 #PHP
You might like
《雄兵连》系列首部大电影《烈阳天道》:可能是因为期望值太高了
2020/08/18 国漫
php新建文件自动编号的思路与实现
2011/06/27 PHP
Thinkphp微信公众号支付接口
2016/08/04 PHP
php语言注释,单行注释和多行注释
2018/01/21 PHP
js sort 二维数组排序的用法小结
2014/01/24 Javascript
toggle()隐藏问题的解决方法
2014/02/17 Javascript
javascript 事件处理示例分享
2014/12/31 Javascript
JS获取图片高度宽度的方法分享
2015/04/17 Javascript
JavaScript中innerHTML,innerText,outerHTML的用法及区别
2015/09/01 Javascript
jQuery随手笔记之常用的jQuery操作DOM事件
2015/11/29 Javascript
jQuery中$.ajax()方法参数解析
2016/10/22 Javascript
Vue中使用vux的配置详解
2017/05/05 Javascript
基于ajax和jsonp的原生封装(实例)
2017/10/16 Javascript
JS获取一个表单字段中多条数据并转化为json格式
2017/10/17 Javascript
vue+express 构建后台管理系统的示例代码
2018/07/19 Javascript
webpack结合express实现自动刷新的方法
2019/05/07 Javascript
深入剖析JavaScript instanceof 运算符
2019/06/14 Javascript
layui导出所有数据的例子
2019/09/10 Javascript
浅谈webpack构建工具配置和常用插件总结
2020/05/11 Javascript
vue 出现data-v-xxx的原因及解决
2020/08/04 Javascript
在vue中配置不同的代理同时访问不同的后台操作
2020/09/11 Javascript
Python字符串和文件操作常用函数分析
2015/04/08 Python
Python模拟三级菜单效果
2017/09/11 Python
python打包生成的exe文件运行时提示缺少模块的解决方法
2018/10/31 Python
解决Pycharm 导入其他文件夹源码的2种方法
2020/02/12 Python
解决Python安装cryptography报错问题
2020/09/03 Python
python中random.randint和random.randrange的区别详解
2020/09/20 Python
总结Pyinstaller的坑及终极解决方法(小结)
2020/09/21 Python
Python jieba结巴分词原理及用法解析
2020/11/05 Python
python实现ping命令小程序
2020/12/28 Python
欧舒丹比利时官网:L’OCCITANE比利时
2017/04/25 全球购物
美国餐厅用品和厨房设备批发网站:KaTom Restaurant Supply
2018/01/27 全球购物
员工自我鉴定范文
2013/10/06 职场文书
产品生产计划书
2014/05/07 职场文书
社团活动总结模板
2014/06/30 职场文书
2016年教师节特级教师获奖感言
2015/12/09 职场文书