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高自定义性安全验证码代码
Nov 27 PHP
用PHP即时捕捉PHP中的错误并发送email通知的实现代码
Jan 19 PHP
简单实用的.net DataTable导出Execl
Oct 28 PHP
PHP 字符串长度判断效率更高的方法
Mar 02 PHP
PHP zip扩展Linux下安装过程分享
May 05 PHP
PHP简单获取多个checkbox值的方法
Jun 13 PHP
PHP获取中国时间(上海时区时间)及美国时间的方法
Feb 23 PHP
Yii 2中的load()和save()示例详解
Aug 03 PHP
PHP下载大文件失败并限制下载速度的实例代码
May 10 PHP
laravel 字段格式化 modle 字段类型转换方法
Sep 30 PHP
深入理解PHP+Mysql分布式事务与解决方案
Dec 03 PHP
一次项目中Thinkphp绕过禁用函数的实战记录
Nov 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
Discuz 模板语句分析及知识技巧
2009/08/21 PHP
php empty函数判断mysql表单是否为空
2010/04/12 PHP
php模拟ping命令(php exec函数的使用方法)
2013/10/25 PHP
ThinkPHP模板循环输出Volist标签用法实例详解
2016/03/23 PHP
简单理解PHP的面向对象编程方式
2016/05/17 PHP
ECSHOP完美解决Deprecated: preg_replace()报错的问题
2016/05/17 PHP
php使用Jpgraph创建3D饼形图效果示例
2017/02/15 PHP
php正则表达式基本知识与应用详解【经典教程】
2017/04/17 PHP
javascript instanceof,typeof的区别
2010/03/24 Javascript
简单常用的幻灯片播放实现代码
2013/09/25 Javascript
Jquery获取元素的父容器对象示例代码
2014/02/10 Javascript
jQuery实现级联菜单效果(仿淘宝首页菜单动画)
2014/04/10 Javascript
情人节单身的我是如何在敲完代码之后收到12束玫瑰的(javascript)
2015/08/21 Javascript
如何让一个json文件显示在表格里【实现代码】
2016/05/09 Javascript
浅谈Node.js轻量级Web框架Express4.x使用指南
2017/05/03 Javascript
requirejs按需加载angularjs文件实例
2017/06/08 Javascript
Vue自定义过滤器格式化数字三位加一逗号实现代码
2018/03/23 Javascript
详解微信小程序用定时器实现倒计时效果
2019/04/30 Javascript
layui插件表单验证提交触发提交的例子
2019/09/09 Javascript
[02:52]DOTA2新手基础教程 米波
2014/01/21 DOTA
[01:00:11]DOTA2-DPC中国联赛 正赛 CDEC vs DLG BO3 第一场 2月7日
2021/03/11 DOTA
python 中文字符串的处理实现代码
2009/10/25 Python
8种常用的Python工具
2020/08/05 Python
用python对oracle进行简单性能测试
2020/12/05 Python
详解CSS3+JS完美实现放大镜模式
2020/12/03 HTML / CSS
阿迪达斯比利时官方商城:adidas比利时
2016/10/10 全球购物
Mamas & Papas沙特阿拉伯:英国最受欢迎的婴儿品牌
2017/11/20 全球购物
欧克利英国官网:Oakley英国
2019/08/24 全球购物
美国最好的葡萄酒网上商店:Wine Library
2019/11/02 全球购物
《小小雨点》教学反思
2014/02/18 职场文书
合同协议书格式
2014/04/18 职场文书
奉献家乡演讲稿
2014/09/13 职场文书
安全隐患整改报告
2014/11/06 职场文书
运动会运动员赞词
2015/07/22 职场文书
小学教代会开幕词
2016/03/04 职场文书
建筑工程挂靠协议书
2016/03/23 职场文书