/**

* 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) {2881064151 
                            $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函数描述及例子的更多相关文章

  1. go每个函数写代码例子

    https://github.com/astaxie/gopkg 由于目前golang的手册里面针对函数的例子太少了,很多时候不知道怎么使用,好多人都是看源代码才明白怎么用,这个给我们快速开发gola ...

  2. OpenGL glMatrixMode() 函数解释与例子

    概述 glMatrixMode() 用以指定当前要操作的矩阵,可选值有 GL_MODELVIEW(模型视图,默认值),GL_PROJECTION(投影),GL_TEXTURE(纹理),GL_COLOR ...

  3. C/C++ 不带参数的回调函数 与 带参数的回调函数 函数指针数组 例子

    先来不带参数的回调函数例子 #include <iostream> #include <windows.h> void printFunc() { std::cout<& ...

  4. Lua rawget rawset newindex 函数定义和例子

    在绝大多数情况下,我们都不会用到rawget和rawset. 本文的运行环境:lua 5.3 for windows rawset 赋值操作 rawset是在设置值的过程,进行处理,比如:当某个值改变 ...

  5. 内联函数背景、例子、与普通函数的区别及要注意的地方 ------新标准c++程序设计

    背景: 使用函数能够避免将相同代码重些多次的烦恼,还能减少可执行程序的体积,但也会带来程序运行时间上的开销.函数调用在执行时,首先在栈中为形参和局部变量分配存储空间,然后还要将实参的值复制给形参,接下 ...

  6. 是否应该学习qt源码(碰到问题的时候,或者文档对函数描述不清楚的时候,可以看一下)

    是否应该学习qt源码 如果你想调用某个函数,但是文档并没有清晰描述这个函数的功能的时候,你就需要去阅读源码,看看Qt究竟是怎么实现的.比如用QNetworkAccessManager发送一个QHttp ...

  7. Python语言中enumerate()及zip()函数的使用例子

    在Python编程语言中,enumerate()及zip()是两个常用的内置函数,这两个函数功能类似,但又有所区别,下面通过两个例子分别进行说明. enumerate()函数 该函数在字面上是枚举.列 ...

  8. 关于Oracle过程,函数的经典例子及解析

    一,Oracle中的过程,函数 对于oracle中的过程和函数,个人觉得可以化为一类,因为它们在写法上并没有什么的不同.公式无非就是 create or replace Package_name(pa ...

  9. 回调函数callback使用例子

    代码如下: <!DOCTYPE HTML> <html> <head> <meta charset="GBK" /> <tit ...

随机推荐

  1. DP:Making the Grade(POJ 3666)

     聪明的修路方案 题目大意:就是农夫要修一条路,现在要求这条路要么就是上升的,要么就是下降的,总代价为∑|a[i]-b[i]|,求代价最低的修路方案, (0 ≤ β≤ 1,000,000,000) , ...

  2. jQuery操作DOM和CSS函数

    function des html jquery result html() 获取元素中HTML内容 <div id="box" style="color:red& ...

  3. ASP.Net核心对象之HttpResponse

    简介: HttpResponse是对响应报文进行设置的一个对象.通过context. Response 能够得到HttpResponse对象. context.Response.Charset;//获 ...

  4. Material Design综合实例

    背景知识 drawlayout的使用 recycleView的使用 CardView的使用 一些开源动画库的使用 ImageView的scaleType属性与adjustViewBounds属性 ,参 ...

  5. eclipse 向HDFS中创建文件夹报错 permission denied

    环境:win7  eclipse    hadoop 1.1.2 当执行创建文件的的时候, 即: String Path = "hdfs://host2:9000"; FileSy ...

  6. 查看TOMCAT的版本

    [root@Apps bin]# sh version.sh Using CATALINA_BASE: /apps/api-tomcat Using CATALINA_HOME: /apps/api- ...

  7. 1.单件模式(Singleton Pattern)

    意图:为了保证一个类仅有一个实例,并提供一个访问它的全局访问点. 1.简单实现(多线程有可能产生多个实例) public class CommonSigleton { /// <summary& ...

  8. oracle 10g 学习之服务器端安装(1)

    Oracle 简介 lOracle 是殷墟出土的甲骨文(oracle bone inscriptions)的英文翻译的第一个单词 lOracle 公司是全球最大的信息管理软件及服务供应商,成立于197 ...

  9. wp8 ListPicker

    如何给selectedindex 绑定SelectedIndex="{Binding User.StationWorkFlag}"  这样写不对嘛 为何提示我 SelectedIn ...

  10. strcat函数造成的段错误(Segmentation fault)

    转自:http://book.51cto.com/art/201311/419441.htm 3.21  strcat函数造成的段错误 代码示例 int main() { char dest[7]=& ...