PHP simplexml Recursive implementation of XML files and arrays of mutual transformation (original)

Source: Internet
Author: User
Tags addchild scalar

One, the XML file is converted to an array
<?php

/*******************************************************/
SimpleXML parsing an XML file is very simple//because it parses the XML file into a large object at once

Here's a simple example.

/************************************************//loading XML document from File//$simxml = simplexml_load_file (' book.xml ');//print _r ($simxml);//echo $simxml->book[1]->title;//View Bokstore There are several books//echo ' there ', $simxml->count (), "book";
Echo $simxml-Asxml (); /*

Use SimpleXML object to convert XML file to array//object with attribute value---------store variable//array with key value--key Values store variable//The difference is not big, JS can be directly regarded as an associative array to operate $simxml = s Implexml_load_file (' Book.xml ');/*print_r ($simxml); echo "<br/>";//cast Print_r of type (array ($simxml)); *///Write a function, recursive SimpleXML object to the group//idea: First the outermost object to the group, and then cycle the conversion//a cell as long as the object, continue to call itself to convert
function Xml2arr ($sim) {$arr = (array) $sim; foreach ($arr as $k + = $v) {if ($v instanceof simplexmlelement | | is_array ($V)) {//Determine if the SimpleXML object or array $arr[$k] = Xml2arr ($v);}} return $arr;}        Print_r ($xmlarr = Xml2arr ($simxml)), Echo $xmlarr [' book '] [' 1 '] [' title ']; At this point, you can manipulate the array directly

?>
Attached to my book.xml content:

<?xml version= "1.0"  encoding= "Utf-8"?><bookstore>    <book  category= "COOKING" >            <title  Lang= "en" >Everyday Italian</title>             <author>Giada De Laurentis</author>             <year>2005</year>             <price>30</price>    </book>     <book category= "Martial Arts" >             <title lang= "Chinese" > Knight line </title>             <author> Jin Yong </author>             <year>2005</year>            <price>29.9</price >    </book>    <book category= "Page" >             <title lang= "Chinese" >php7 </title>             <author>lover Snow </author>             <year>2003</year>             <price>30.99</price>     </book>            <book  category= "novel" >            <title  lang= "en" > From Song </title>            < Author> Beauty writer &LT;/AUTHOR&GT;&Nbsp;           <year>2001</year>             <price>49.99</price>     </book></bookstore> 


  Second, array to XML file

Nonsense, start with a simple one-dimensional array:
(1), one-dimensional array to XML
        

<?php//one-dimensional array into xml//************************************************//one-dimensional array to xml//**************************** Idea: Loop through each cell in the array and add it to the XML document node $arr = array (          ' name ' = ' lover Snow ',         ' content ' = ' I like Snow ', Function arr2xml ($arr) {        //Direct value string           $simxml  = new simplexmlelement (' <?xml version= ' 1.0   encoding= "Utf-8"  ?><root></root> "        foreach"; ($arr  as  $k + $v) {                 $simxml AddChild ($k, $v);        }         return  $simxml->savexml ();} Header (' Content-type: text/xml ');echo  ($str &NBSP;=&NBSP;ARR2XML ($arr)); File_put_contents ('./01.xml ', $str); ?>   Next, we'll change it in the code above for a multidimensional array

(2), multidimensional array converted to XML

 <?php//multidimensional array to xml//idea: Loop through each cell in the array and add it to the XML document node $arr = array (          ' name ' = ' lover Snow ',         ' content ' and ' I like Snow ',          ' job ' =>array (                  ' title ' + ' manager ',                  ' Salary ' =>8888,                  ' team ' =>array ("Lover Snow", "Silence", ' hurts ')          ) Function arr2xml ($arr, $node =null) {         //Direct Value String         if (Is_null ($node))                   $simxml  =  New simplexmlelement (' &Lt;? Xml version= "1.0"  encoding= "Utf-8"  ?><root></root> ";         else                  $simxml  =  $node;         foreach ($arr   as  $k = $v) {            //if array                  if (Is_array ($v)) {                          arr2xml ($v, $simxml->addchild ($k));                 }else if (Is_numeric ($k)) {        //If the node name is a number, the XML tag must not have a number start                           $simxml->addchild (' item '. $k,  $v);                 }else{               //is a string//if (Is_scalar ($v))//scalar type:bool   float  interage string                          $simxml->addchild ($k, $v);                 }         }        return  $simxml SaveXML ();} Header (' Content-type: text/xml ');echo  ($str  = arr2xml ($arr)); File_put_contents ('./01.xml '), $STR);? >   in the above code, in Ar2xml, first in the parameter, add a $node node, as the root node when the $arr array is used,
If the incoming $node is empty, then there is no root node, we can create a root node,
Otherwise, directly add the nodes created later as child nodes of the $node,

It is discussed in three situations, namely, arrays, numbers, and all scalar types.
The reason for classifying numbers separately is because, in XML, tags are not allowed to start with numbers.

The result graph is as follows: The content is finally written to the file, and 01 is created in the current directory. XML file.







PHP simplexml Recursive implementation of XML files and arrays of mutual transformation (original)

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.