A simple conversion between XML and an array

Source: Internet
Author: User
Tags addchild closing tag rewind string format tag name

XML is the most widely used data interchange format in the network, so you don't know how to manipulate it, and you have a sore egg.

There are many classes/functions in PHP that can manipulate XML, and personally think the simplest is the SimpleXMLElement class, which uses the same name: simple. Of course, if you want to manipulate XML fully and freely, you have to use other classes as well. SimpleXMLElement is mainly the addition and acquisition of XML nodes, as well as the output of the entire XML text content, but for the implementation of a simple and the content between the array conversion, is sufficient.

For example, we are now receiving an SDK, the interface is a simple XML format data, we need to take it, and do some processing, and finally return to it, and return is still XML format. Can let us deal with the ease of the format, of course the array for the best.

First of all, this method can handle the XML format is very special (later will say that the code can not handle the situation), such as the following:

<response>

<title>entity</title>

<name>toy</name>

<price>32.00</price>

<date>2014-01-03 15:25:36</date>

</response>

First it must be contained within a total opening and closing tag, of course, which is the XML must be formatted. Then its element name must be a non-numeric string, but also can not have duplicate tag elements, the limit is very dead, so only as a local simple data exchange, really say to transfer complex XML files, play does not turn.

In the SimpleXMLElement class, there is a addChild method that adds an XML node that returns a variable that points to the node object. The constructors of the SimpleXMLElement class are either simplexml_load_string, Simplexml_load_file methods, Allows us to construct a SimpleXMLElement class from another file or from an XML string, and its Asxml method returns a normalized XML format string data. For example, there is now an empty, string XML format Data "<xml><a>hello</a></xml>", using the Addchild method:

    $str= ' <xml><a>hello</a></xml> '; $sxe=simplexml_load_string($str); if($sxe){        $cha=$sxe->addchild (' Cha ');//add an empty label element        $cha->addchild (' person ', ' Jack ')); $cha->addchild (' person ', ' perter ');//add two person tag, the second parameter corresponding to the value        Echo $sxe-Asxml (); }

Output in asxml format is like this.

The whole heap is together, the Asxml method only returns the text content of the node, that is, the string value of the node, so the XML structure is not visible. Right-click on the source code or the chrome review element to see its original appearance:

The <xml> element is the root node of the entire XML data, and in the beginning only the <a> element,<cha> element and its two child elements <person> are added by code, using the Addchild method.

The general idea of the transformation is to convert from an array to XML, with the key as the element name, the corresponding value as the value of the element, in turn from the XML to the array, the element as the key of the array, the element value as the corresponding value. The problem is that XML does not allow a pure number to be the element name, and if the array has a numeric or numeric string as the key name, it will fail when converted to XML, and if the XML is in the same generation (<a type= "OK") with the same element name (at the same level) from the XML to the array. >aaa </a> I like to refer to a as an element name, AAA is called an element value, type is called a property name, OK is called a property value, and the value of the element behind it overrides the value of the previous element, which is also the beginning of a small example of passing an array, where there are no elements of the same element name.

1. Array to XML

First the foreach array, get the key and value, if the value is scalar (of course, will not pass the object and so on type, unless serialized, etc.), the element is directly added to the SimpleXMLElement object, the element name is the key name, the element value when the key corresponding value; If the value is an array, an empty element is added first. The element name is the key name, and then its corresponding array is processed again in the previous steps, which obviously requires recursion.

<?PHP/** Array to XML @param arr array @param arr null| SimpleXMLElement return String*/    functionArraytoxml ($arr,$sxe=NULL){        $str= ' <xmlData></xmlData> '; if($sxeinstanceof SimpleXMLElement) {            $xmlDoc=$sxe; }        Else{            $xmlDoc=NewSimpleXMLElement ($str); }                foreach($arr  as $key=$val){        if(Is_array($val)){            $child=$xmlDoc->addchild ($key); Arraytoxml ($val,$child); }        Else{            $xmlDoc->addchild ($key,$val); }        return $xmlDoc-Asxml (); }    //Test    $arr=Array(' a ' = ' aaa ', ' b ' = ' BBB ', ' c ' = =Array(' d ' =>1, ' e ' =>2, ' f ' = ' fff ')); $xml= Arraytoxml ($arr); Echo $xml.‘ <br/> ';

Effect:

The <b> elements are processed into HTML tags. If you want to make some improvements, one can deal with the case of the key in the array is a number or a string of numbers, such as the same name NUM, because the XML data allows multiple identical element names exist, and the second is that our local editor may encode code when it is not required by the other, you can do the code conversion, Transfer to the other side, the following is the improved

<?PHP/** Array to XML @param arr array @param arr null| SimpleXMLElement return String*/    functionArraytoxml ($arr,$sxe=NULL){        $str= ' <xmlData></xmlData> '; if($sxeinstanceof SimpleXMLElement) {            $xmlDoc=$sxe; }        Else{            $xmlDoc=NewSimpleXMLElement ($str); }                foreach($arr  as $key=$val){            if(Is_array($val)){                            if(Is_numeric($key)){//Generally, tags in XML are alphabetic strings.                    $child=$xmlDoc->addchild (' num ');//Add a new label and return the variable that points to the new label                }                Else{                    $child=$xmlDoc->addchild ($key); } arraytoxml ($val,$child);//inserts an element from a sub-array on the node based on the current child node as an object            }            Else{                $val= Mb_convert_encoding ($val, ' UTF-8 '); if(Is_numeric($key)){                    $xmlDoc->addchild (' num ',$val); }                Else{                    $xmlDoc->addchild ($key,$val); }            }        }        return $xmlDoc-Asxml (); }    //Test    $arr=Array(' a ' = ' aaa ', 5, ' 1 ' = ' bbb ', ' c ' =Array(1, 2, ' f ' = ' fff ')); $xml= Arraytoxml ($arr); Echo $xml.‘ <br/> ';

Effect:

You can see that the numeric key names are replaced with the NUM element names, which are not overwritten by the same XML element name.

2. XML-to-array

XML to the array, you need to traverse the XML element node, take their element name and element value, SimpleXMLElement class does not have these traversal methods, need to use its subclass Simplexmliterator, a look at the name to know that this class is designed for iteration, traversal prepared. It not only integrates simplexmlelement, but also implements recursive iterators and statistics interfaces, and when traversing an XML object, it mainly uses several methods:

Current (void) returns the present element

Key (Viod) returns the current element name

HasChildren (void) to determine whether the current element has child elements

Valid (void) determines whether the currently pointing element is valid, and the next one that iterates to the last element of the object is invalid

Next (void) points to the next element

Rewind (void) Sets the element that points to the beginning of the object

Note that the first element pointing to the object is pointing to the <a> in the bottom, rather than the <xml>,<xml> is the element that contains the entire XML data, and it is important to note that, of course, if you want to study the XML carefully, Also have to look specifically at its definition use, of course there are many other places to set

<xml>

<a>a</a>

<b>b</b>

</xml>

The idea of conversion is that if the incoming object is not (at first, it must be passed an XML string in), first create the Simplexmliterator object, and then traverse the object element, if the element does not have child elements, its element name as the key, the element value as the corresponding value into the array, if there are child elements , the element name is taken out, as a key, and the child element variable is passed to the method, recursive return, the code is as follows

<?PHP/** XML-to-array @param xml string| Simplexmliterator return Array*/    functionXmltoarray ($xml){        $ret=Array(); if($xmlinstanceof SimpleXMLElement) {            $xmlDoc=$xml; }        Else{            $xmlDoc=simplexml_load_string($xml, ' Simplexmliterator '); if(!$xmlDoc){//problem with XML string format                return NULL; }        }                 for($xmlDoc-Rewind();$xmlDoc->valid ();$xmlDoc-Next()){            $key=$xmlDoc-Key();//Get tag name            $val=$xmlDoc- Current();//Get current tab            if($xmlDoc->haschildren ()) {//If there are child elements                $ret[$key] = Xmltoarray ($val);//recursive processing of child element variables returns            }            Else{                $ret[$key] = (string)$val; }        }        return $ret; }    $xmlstr= ' <xml><name>cat</name><color>black</color><feature><weight>1.0kg </weight>; $array= Xmltoarray ($xmlstr); Echo' XML to Array=><pre> '; Print_r($array);

Printing results:

If there is the same element name under the same generation, the back will cover the front, so the scope of use is still limited.

A simple conversion between XML and an array

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.