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,JS,CSS等标签
Jan 16 PHP
php下关于中英数字混排的字符串分割问题
Apr 06 PHP
PHPCMS的使用小结
Sep 20 PHP
php做下载文件的实现代码及文件名中乱码解决方法
Feb 03 PHP
PHP 实现explort() 功能的详解
Jun 20 PHP
探讨:web上存漏洞及原理分析、防范方法
Jun 29 PHP
开源php中文分词系统SCWS安装和使用实例
Apr 11 PHP
PHP两种快速排序算法实例
Feb 15 PHP
php判断访问IP的方法
Jun 19 PHP
Smarty分页实现方法完整实例
May 11 PHP
PHP实现超简单的SSL加密解密、验证及签名的方法示例
Aug 28 PHP
PHP 获取 ping 时间的实现方法
Sep 29 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桌面中心(一) 创建数据库
2007/03/11 PHP
探讨Smarty中如何获取数组的长度以及smarty调用php函数的详解
2013/06/20 PHP
php时间计算相关问题小结
2016/05/09 PHP
PHP开发之归档格式phar文件概念与用法详解【创建,使用,解包还原提取】
2017/11/17 PHP
javascript 一段左右两边随屏滚动的代码
2009/06/18 Javascript
Javascript实现滑块滑动改变值的实现代码
2013/04/12 Javascript
使用Jquery实现点击文字后变成文本框且可修改
2013/09/21 Javascript
点击button获取text内容并改变样式的js实现
2014/09/09 Javascript
js QQ客服悬浮效果实现代码
2014/12/12 Javascript
jquery实现初次打开有动画效果的网页TAB切换代码
2015/09/06 Javascript
基于socket.io+express实现多房间聊天
2016/03/17 Javascript
Base64(二进制)图片编码解析及在各种浏览器的兼容性处理
2017/02/09 Javascript
彻底解决 webpack 打包文件体积过大问题
2017/07/07 Javascript
vue+iview写个弹框的示例代码
2017/12/05 Javascript
Vue 动态添加路由及生成菜单的方法示例
2019/06/20 Javascript
js实现从右往左匀速显示图片(无缝轮播)
2020/06/29 Javascript
JavaScript 防盗链的原理以及破解方法
2020/12/29 Javascript
python不带重复的全排列代码
2013/08/13 Python
用C++封装MySQL的API的教程
2015/05/06 Python
wxPython定时器wx.Timer简单应用实例
2015/06/03 Python
Python实现 多进程导入CSV数据到 MySQL
2017/02/26 Python
批量获取及验证HTTP代理的Python脚本
2017/04/23 Python
python爬虫入门教程--快速理解HTTP协议(一)
2017/05/25 Python
Python对切片命名的实现方法
2018/10/16 Python
使用python telnetlib批量备份交换机配置的方法
2019/07/25 Python
18个Python脚本可加速你的编码速度(提示和技巧)
2019/10/17 Python
python中xlutils库用法浅析
2020/12/29 Python
Columbia Sportswear法国官网:全球户外品牌
2020/09/25 全球购物
汉语专业应届生求职信
2013/10/01 职场文书
工厂实习感言
2014/01/14 职场文书
单位工程竣工验收方案
2014/03/16 职场文书
《青山处处埋忠骨》教学反思
2014/04/22 职场文书
教师党员个人自我剖析材料
2014/09/29 职场文书
教师听课学习心得体会
2016/01/15 职场文书
Python实现生活常识解答机器人
2021/06/28 Python
Python将CSV文件转化为HTML文件的操作方法
2021/06/30 Python