Conversion Between XML arrays and objects and between xml Arrays
Why do we need to switch between them? Because of the troubles, programmers are disgusted with the troubles.
1 array to xml
<? Php/* idea of converting one-dimensional array to xml: add each unit in the loop array to the xml document node * // * $ arr = array ('name' => 'twent ', 'age' => 29); function arr2xml ($ arr) {$ simxml = new simpleXMLElement ('<? Xml version = "1.0" encoding = "UTF-8"?> <Root> </root> '); // how to add a subnode to the simpleXMLElement object? Foreach ($ arr as $ k =>$ v) {$ simxml-> addChild ($ k, $ v);} return $ simxml-> saveXML ();} */$ arr = array ('name' => 'ding 3', 'age' => 29, 'job' => array ('title' => 'manager ', 'salary '=> 8888, 'team' => array ('red', 'xiaoming', 'hua '); function arr2xml ($ arr, $ node = null) {if ($ node = null) {$ simxml = new simpleXMLElement ('<? Xml version = "1.0" encoding = "UTF-8"?> <Root> </root> ');} How does the else {$ simxml = $ node;} // Add a subnode to the simpleXMLElement object? Foreach ($ arr as $ k =>$ v) {if (is_array ($ v) {// $ simxml-> addChild ($ k); arr2xml ($ v, $ simxml-> addChild ($ k);} else if (is_numeric ($ k) {// The tag cannot start with a number, similar to the variable $ simxml-> addChild ('item '. $ k, $ v);} else {$ simxml-> addChild ($ k, $ v);} return $ simxml-> saveXML ();} header ('content-type: text/xml'); echo arr2xml ($ arr );
Running result:
2 xml to array
<? Php/*** // use-> and [] for access. inconvenient // next we will practice converting xml to array echo $ simxml-> book [0]-> title; converting xml files into Arrays Using simplexml objects, * ** // * The object uses the property name-> attribute value, and the storage variable array uses the key name-> key value to store the variable. The difference is not big. In js, objects can be operated as associated arrays. */$ simxml = simplexml_load_file ('. /book. xml ');/* print_r ($ simxml); echo'