This article mainly introduces the mutual conversion function of php to realize XML and array, and analyzes the related operation skills of php to realize xml to array and array to xml in combination with examples. Friends in need can refer to this article
The example describes the mutual conversion function of XML and array in PHP. Share it with everyone for your reference, the details are as follows:
Convert array 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 to array:
function xmltoarr($path){ $xmlfile = file_get_contents($path);//提取xml文档中的内容以字符串格式赋给变量 $ob= simplexml_load_string($xmlfile);//将字符串转化为变量 $json = json_encode($ob);//将对象转化为JSON格式的字符串 $configData = json_decode($json, true);//将JSON格式的字符串转化为数组 print_r($configData); }
For more examples of mutual conversion functions between XML and arrays in PHP, please pay attention to the PHP Chinese website!