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与MySQL交互使用详解
Oct 09 PHP
PHP的几个常用数字判断函数代码
Apr 24 PHP
php调用mysql存储过程实例分析
Dec 29 PHP
php关键字仅替换一次的实现函数
Oct 29 PHP
php nginx 实时输出的简单实现方法
Jan 21 PHP
php爬取天猫和淘宝商品数据
Feb 23 PHP
PHP使Laravel为JSON REST API返回自定义错误的问题
Oct 16 PHP
PDO::inTransaction讲解
Jan 28 PHP
Thinkphp5+plupload实现的图片上传功能示例【支持实时预览】
May 08 PHP
Laravel自动生成UUID,从建表到使用详解
Oct 24 PHP
laravel框架使用FormRequest进行表单验证,验证异常返回JSON操作示例
Feb 18 PHP
THINKPHP5分页数据对象处理过程解析
Oct 28 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
ThinkPHP标签制作教程
2014/07/10 PHP
php版微信公众平台实现预约提交后发送email的方法
2016/09/26 PHP
thinkphp jquery实现图片上传和预览效果
2020/07/22 PHP
php中通用的excel导出方法实例
2017/12/30 PHP
默认让页面的第一个控件选中的javascript代码
2009/12/26 Javascript
jQuery的三种$()
2009/12/30 Javascript
基于jquery的内容循环滚动小模块(仿新浪微博未登录首页滚动微博显示)
2011/03/28 Javascript
关于跨站脚本攻击问题
2011/12/22 Javascript
javascript全局变量封装模块实现代码
2012/11/28 Javascript
window.event.keyCode兼容IE和Firefox实现js代码
2013/05/30 Javascript
JavaScript的类型、值和变量小结
2015/07/09 Javascript
Bootstrap打造一个左侧折叠菜单的系统模板(一)
2016/05/17 Javascript
jquery中的常见问题及快速解决方法小结
2016/06/14 Javascript
js仿腾讯QQ的web登陆界面
2016/08/19 Javascript
jQuery.parseHTML() 函数详解
2017/01/09 Javascript
浅谈vue项目可以从哪些方面进行优化
2018/05/05 Javascript
react实现点击选中的li高亮的示例代码
2018/05/24 Javascript
vue 中动态绑定class 和 style的方法代码详解
2018/06/01 Javascript
JS通过识别id、value值对checkbox设置选中状态
2020/02/19 Javascript
javascript如何使用函数random来实现课堂随机点名方法详解
2020/07/28 Javascript
Python实现爬虫爬取NBA数据功能示例
2018/05/28 Python
Python数据类型之List列表实例详解
2019/05/08 Python
python 实现将list转成字符串,中间用空格隔开
2019/12/25 Python
通过python实现windows桌面截图代码实例
2020/01/17 Python
Python爬虫实现模拟点击动态页面
2020/03/05 Python
Pyinstaller 打包发布经验总结
2020/06/02 Python
Pytorch损失函数nn.NLLLoss2d()用法说明
2020/07/07 Python
Python 打印自己设计的字体的实例讲解
2021/01/04 Python
matplotlib相关系统目录获取方式小结
2021/02/03 Python
材料成型专业个人求职信范文
2013/09/25 职场文书
优秀干部获奖感言
2014/01/31 职场文书
生产部厂长助理职位说明书
2014/03/03 职场文书
入党自我鉴定
2014/03/25 职场文书
天网工程实施方案
2014/03/26 职场文书
初三毕业感言
2015/07/31 职场文书
Nginx安装完成没有生成sbin目录的解决方法
2021/03/31 Servers