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 相关文章推荐
PHP4之真OO
Oct 09 PHP
PHP中函数内引用全局变量的方法
Oct 20 PHP
php新建文件自动编号的思路与实现
Jun 27 PHP
PHP修改session_id示例代码
Jan 08 PHP
Thinkphp中的curd应用实用要点
Jan 04 PHP
php将数组存储为文本文件方法汇总
Oct 28 PHP
Zend Framework实现Zend_View集成Smarty模板系统的方法
Mar 05 PHP
Symfony2框架学习笔记之HTTP Cache用法详解
Mar 18 PHP
thinkphp在低版本Nginx 下支持PATHINFO的方法分享
May 27 PHP
yii2控制器Controller Ajax操作示例
Jul 23 PHP
php array_walk 对数组中的每个元素应用用户自定义函数详解
Nov 18 PHP
PHP依赖注入原理与用法分析
Aug 21 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巧获服务器端信息
2006/12/06 PHP
PHP判断文件是否被引入的方法get_included_files用法示例
2016/11/29 PHP
Laravel构建即时应用的一种实现方法详解
2017/08/31 PHP
JS获取scrollHeight问题想到的标准问题
2007/05/27 Javascript
用JavaScript修改CSS属性的代码
2013/05/06 Javascript
解决jquery操作checkbox火狐下第二次无法勾选问题
2014/02/10 Javascript
JavaScript获取flash对象与网上的有所不同
2014/04/21 Javascript
Javascript removeChild()删除节点及删除子节点的方法
2015/12/27 Javascript
js+css简单实现网页换肤效果
2015/12/29 Javascript
浅析JavaScript动画模拟拖拽原理
2016/12/09 Javascript
原生js更改css样式的两种方式
2017/03/15 Javascript
AngularJS2中一种button切换效果的实现方法(二)
2017/03/27 Javascript
Angular2 之 路由与导航详细介绍
2017/05/26 Javascript
web前端vue filter 过滤器
2018/01/12 Javascript
Node.js Buffer用法解读
2018/05/18 Javascript
Angularjs实现多图片上传预览功能
2018/07/18 Javascript
vue+iview动态渲染表格详解
2019/03/19 Javascript
深入浅析vue-cli@3.0 使用及配置说明
2019/05/08 Javascript
js基础之事件捕获与冒泡原理
2019/10/09 Javascript
LayUi数据表格自定义赋值方式
2019/10/26 Javascript
[05:02][DOTA2]DOTA进化论 第一期
2013/09/27 DOTA
Django Admin实现三级联动的示例代码(省市区)
2018/06/22 Python
python matlibplot绘制3D图形
2018/07/02 Python
Python字典生成式、集合生成式、生成器用法实例分析
2020/01/07 Python
对django 2.x版本中models.ForeignKey()外键说明介绍
2020/03/30 Python
keras的ImageDataGenerator和flow()的用法说明
2020/07/03 Python
如何在Canvas上的图形/图像绑定事件监听的实现
2020/09/16 HTML / CSS
意大利网上书店:LaFeltrinelli
2020/06/12 全球购物
Java中实现多态的机制是什么?
2014/12/07 面试题
学年末自我鉴定
2014/01/21 职场文书
创业女性典型材料
2014/05/02 职场文书
小学生运动会通讯稿
2014/09/23 职场文书
思想政治表现评语
2015/01/04 职场文书
清洁员岗位职责
2015/02/15 职场文书
2015国庆节宣传语
2015/07/14 职场文书
Go 语言中 20 个占位符的整理
2021/10/16 Golang