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 相关文章推荐
php中判断文件空目录是否有读写权限的函数代码
Aug 07 PHP
php导出word文档与excel电子表格的简单示例代码
Mar 08 PHP
windows下安装php的memcache模块的方法
Apr 07 PHP
php+ajax实现的点击浏览量加1
Apr 16 PHP
php采用session实现防止页面重复刷新
Dec 24 PHP
thinkPHP中多维数组的遍历方法
Jan 09 PHP
如何使用PHP给图片加水印
Oct 12 PHP
PHP登录(ajax提交数据和后台校验)实例分享
Dec 29 PHP
PHP单例模式与工厂模式详解
Aug 29 PHP
PHP生成随机数的方法总结
Mar 01 PHP
JSON PHP中,Json字符串反序列化成对象/数组的方法
May 31 PHP
laravel-admin 在列表页添加自定义按钮的例子
Sep 30 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
PHP设计模式之迭代器模式
2016/06/17 PHP
Thinkphp3.2实用篇之计算型验证码示例
2017/02/09 PHP
Yii2 hasOne(), hasMany() 实现三表关联的方法(两种)
2017/02/15 PHP
PHP面向对象五大原则之里氏替换原则(LSP)详解
2018/04/08 PHP
PHP实现 APP端微信支付功能
2018/06/22 PHP
PHP利用Mysql锁解决高并发的方法
2018/09/04 PHP
javascript模拟select,jselect的方法实现
2012/11/08 Javascript
从数据结构的角度分析 for each in 比 for in 快的多
2013/07/07 Javascript
用js实现in_array的方法
2013/11/05 Javascript
为什么JS中eval处理JSON数据要加括号
2015/04/13 Javascript
JS模态窗口返回值兼容问题的完美解决方法
2016/05/28 Javascript
详解Node.js access_token的获取、存储及更新
2017/06/20 Javascript
jquery实现左右轮播图效果
2017/09/28 jQuery
Angular.js实现获取验证码倒计时60秒按钮的简单方法
2017/10/18 Javascript
Angular8路由守卫原理和使用方法
2019/08/29 Javascript
JS自定义右键菜单实现代码解析
2020/07/16 Javascript
浅谈JSON5解决了JSON的两大痛点
2020/12/14 Javascript
python操作mysql中文显示乱码的解决方法
2014/10/11 Python
Python random模块常用方法
2014/11/03 Python
用Python进行行为驱动开发的入门教程
2015/04/23 Python
python实现连接mongodb的方法
2015/05/08 Python
Python3中使用PyMongo的方法详解
2017/07/28 Python
python将字符串以utf-8格式保存在txt文件中的方法
2018/10/30 Python
Python实现的文轩网爬虫完整示例
2019/05/16 Python
python pandas获取csv指定行 列的操作方法
2019/07/12 Python
测试时代收集的软件测试面试题
2013/09/25 面试题
仓管岗位职责范本
2014/02/08 职场文书
大学生素质拓展活动方案
2014/02/11 职场文书
班风学风建设方案
2014/05/06 职场文书
质量在我心中演讲稿
2014/09/02 职场文书
企业总经理助理岗位职责
2014/09/12 职场文书
工作证明范本(2篇)
2014/09/14 职场文书
卖车协议书范本4篇
2014/10/01 职场文书
胡桃夹子观后感
2015/06/11 职场文书
幼儿园庆六一主持词
2015/06/30 职场文书
应届生个人的求职(自荐信范文2篇)
2019/08/23 职场文书