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中动态HTML的输出技术
Oct 09 PHP
discuz 首页四格:最新话题+最新回复+热门话题+精华文章插件
Aug 19 PHP
解析:使用php mongodb扩展时 需要注意的事项
Jun 18 PHP
PHP函数addslashes和mysql_real_escape_string的区别
Apr 22 PHP
PHP中定义数组常量(array常量)的方法
Nov 17 PHP
php获取、检查类名、函数名、方法名的函数方法
Jun 25 PHP
php打乱数组二维数组多维数组的简单实例
Jun 17 PHP
php获取文件名称和扩展名的方法
Feb 07 PHP
PHP抽象类与接口的区别详解
Mar 21 PHP
PHP实现15位身份证号转18位的方法分析
Oct 16 PHP
详解phpstorm2020最新破解方法
Sep 17 PHP
PHP读取文件或采集时解决中文乱码
Mar 09 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写出自己的BLOG系统 2
2010/04/12 PHP
js代码实现微博导航栏
2015/07/30 PHP
分享ThinkPHP3.2中关联查询解决思路
2015/09/20 PHP
windows下的WAMP环境搭建图文教程(推荐)
2017/07/27 PHP
jQuery 使用手册(四)
2009/09/23 Javascript
有道JavaScript监听浏览器的问题
2010/06/23 Javascript
js操作输入框中选择内容兼容IE及其他主流浏览器
2014/04/22 Javascript
jquery获取radio值(单选组radio)
2014/10/16 Javascript
详细分析JavaScript变量类型
2015/07/08 Javascript
js实现input框文字动态变换显示效果
2015/08/19 Javascript
JS全局变量和局部变量最新解析
2016/06/24 Javascript
js实现九宫格拼图小游戏
2017/02/13 Javascript
微信小程序动态添加分享数据
2017/06/14 Javascript
详解vue-cli官方脚手架配置
2018/07/20 Javascript
Angular刷新当前页面的实现方法
2018/11/21 Javascript
微信小程序当前时间时段选择器插件使用方法详解
2018/12/28 Javascript
浅谈Vue2.4.0 $attrs与inheritAttrs的具体使用
2020/03/08 Javascript
Vue性能优化的方法
2020/07/30 Javascript
vue中配置scss全局变量的步骤
2020/12/28 Vue.js
Python学习之Django的管理界面代码示例
2018/02/10 Python
pandas数据预处理之dataframe的groupby操作方法
2018/04/13 Python
python读取指定字节长度的文本方法
2019/08/27 Python
解决flask接口返回的内容中文乱码的问题
2020/04/03 Python
解决pycharm不能自动保存在远程linux中的问题
2021/02/06 Python
HTML5 canvas基本绘图之图形组合
2016/06/27 HTML / CSS
美国婚戒购物网站:Anjays Designs
2017/06/28 全球购物
法国高保真音响和家庭影院商店:Son Video
2019/04/26 全球购物
夜大毕业自我鉴定
2013/10/11 职场文书
应届生求职信写作技巧
2013/10/24 职场文书
十八届三中全会报告学习材料
2014/02/17 职场文书
大学奖学金获奖感言
2014/08/15 职场文书
党员批评与自我批评发言材料
2014/10/14 职场文书
干部培训工作总结2015
2015/05/25 职场文书
springboot如何初始化执行sql语句
2021/06/22 Java/Android
纯html+css实现奥运五环的示例代码
2021/08/02 HTML / CSS
Vue如何清空对象
2022/03/03 Vue.js