Home > Backend Development > PHP Tutorial > Code sharing for converting xml to array using php

Code sharing for converting xml to array using php

WBOY
Release: 2016-07-25 08:57:20
Original
1225 people have browsed it
How to convert xml data into simple and easy-to-read array data? The code shared in this article can achieve this function. Friends in need should take a look.

The following code implements the function of converting xml into an array. Example:

<?php
/**
* 转换xml为数组
* edit by bbs.it-home.org
*/
class xml {  
    private $parser;  
    private $tag_cur=0;  
    private $data=array();  
    private $struct=array();  
    function xml() {  
        $this->parser = xml_parser_create();  
        xml_set_object($this->parser,&$this);  
        xml_set_element_handler($this->parser,"tag_open","tag_close");  
        xml_set_character_data_handler($this->parser,"cdata");  
    }  
    function parse($data) {  
        $this->data=array();  
        $this->struct=array();  
        $this->tag_cur=0;  
        xml_parse($this->parser,$data);  
        return $this->data;  
    }  
    function tag_open($parser,$tag,$attributes) {  
        $this->struct[]=$tag;  
        $this->tag_cur++;  
    }  
    function cdata($parser,$cdata) {  
        $tmp=&$this->data;  
        for($i=0;$i<$this->tag_cur;$i++)  
        {  
            if(!isset($tmp[$this->struct[$i]]))  
            {  
                $tmp[$this->struct[$i]]=array();  
            }  
            $tmp=&$tmp[$this->struct[$i]];  
        }  
        if(!empty($tmp))  
        {  
            $tmp1=$tmp;  
            if(is_array($tmp1))  
            {  
                $tmp=array_merge($tmp1,array($cdata));  
            }else{  
                $tmp=array($tmp1,$cdata);  
            }  
        }else $tmp=$cdata;  
    }  
    function tag_close($parser,$tag) {  
        array_pop($this->struct);  
        $this->tag_cur--;  
    }  
}  
  
$xml=new xml();  
echo "<pre class="brush:php;toolbar:false">";  
print_r($xml->parse('<b1>b1</b1><b2>b2</b2><b3><c1><d1>d1</d1>
<d1>d1_2</d1><d1>d1_3</d1></c1></b3></a1><e1>1</e1>'));  
echo "
Copy after login
"; ?>

Instructions: You can also use the simplexml_load_string function to easily do this.



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template