This article mainly introduces php's ability to convert XML and arrays into one another, and analyzes the xml-to-array and array-to-xml operations in the form of examples, for more information about how to convert XML and arrays in php, see the next article. This article describes how to convert xml to arrays in php and how to convert arrays to xml using examples, for more information, see
This example describes how php converts XML and arrays. We will share this with you for your reference. The details are as follows:
Convert arrays to xml:
function arrtoxml($arr,$dom=0,$item=0){ if (!$dom){ $dom = new DOMDocument("1.0"); } if(!$item){ $item = $dom->createElement("root"); $dom->appendChild($item); } foreach ($arr as $key=>$val){ $itemx = $dom->createElement(is_string($key)?$key:"item"); $item->appendChild($itemx); if (!is_array($val)){ $text = $dom->createTextNode($val); $itemx->appendChild($text); }else { arrtoxml($val,$dom,$itemx); } } return $dom->saveXML();}
Convert xml into an array:
Function xmltoarr ($ path) {$ xmlfile = file_get_contents ($ path); // extract the content in the xml document and assign it to the variable $ ob = simplexml_load_string ($ xmlfile) in string format ); // convert the string to the variable $ json = json_encode ($ ob); // Convert the object to a JSON string $ configData = json_decode ($ json, true ); // Convert a JSON string to an array print_r ($ configData );}
For more articles about how to convert XML and array functions in php, refer to PHP!