1. Xml to Array
Steps:
(1) First convert an XML file to an object using SimpleXML
(2) Since there are arrays in this object, and objects are contained within the array, we use recursion to strongly convert each object to a group
Conversion code:
<?php/** * XML Conversion Array *@author WEBBC * *functionXml2arr($simxml) {$simxml = (Array $simxml; //strong turn foreach ( $simxml as $k = $v) { if (Is_array ( $v) | | is_object ( $v) { $simxml [ $k] = Xml2arr ($ V); }} return $simxml;} $simxml = simplexml_load_file (//This object has both arrays and objects that are not very convenient to use, you can try to convert this object to an array of //print_r ($simxml);p Rint_r ( Xml2arr ( $simxml)); ?>
(3) Conversion of one-dimensional arrays to XML data
Code:
<?php/** * One-dimensional array to XML *@author WEBBC * *$arr =Array' Name ' + =' WEBBC ',' Age ' =' 22 ',);The array to convertConversion functionsfunctionArr2xml($arr) {$simxml =New SimpleXMLElement (' <?xml version= ' 1.0 ' encoding= ' utf-8 '?><root></root> '); //Create SimpleXML Object //iterate array, loop to add to the root node foreach ($arr as $k + $v) { $simxml AddChild ($k,$v);} //Return XML Data Header (' Content-type:text/xml;charset=utf-8 '); return $simxml->savexml ();} Echo arr2xml ($arr); Output to browser ?>
(4) Multidimensional data conversion to XML
Code:
<?php/** * Multidimensional Array goto XML *@author WEBBC * *$arr =Array' Name ' + =' WEBBC ',' Age ' =' 22 ',' Job ' =Array' Title ' =' Sales manager ',' Salary ' =' 12K ',' Team ' =Array' Xiao Ming ',' Xiao Hua ',' Kobayashi '));The multidimensional array information to convertConversion functionsfunctionArr2xml($arr,$parentNode =null) {If the parent node is null, the root node is created or the parent node is usedIf$parentNode = = =NULL) {$simxml =New SimpleXMLElement (' <?xml version= ' 1.0 ' encoding= ' utf-8 '?><root></root> '); }else{$simxml =$parentNode; }Iterating through an arrayforeach$arrAs$k =$V) {if (Is_array ($v)) {If it is an array, the recursive call continues and the parent node is created with the key value Arr2xml ($v,$simxml->addchild ($K)); }else if (is_numeric ( $k)) {//if the key value is a number, you cannot use a pure number as the label name of the XML, so the ' item ' character is added here, this character can be customized $simxml- >addchild ( "item". $k, $v); }else{//add node $simxml- AddChild ( $k, $v);}} //Return Data header ( ' content-type:text/xml;charset=utf-8 '); return $simxml->savexml ();} echo arr2xml ( $arr); ?>
< Span class= "hljs-comment" >< Span class= "Hljs-keyword" > &NBSP;
Conversion of XML to array