This article mainly introduces the PHP implementation of XML and arrays of the mutual transformation function, combined with the example of PHP to implement XML-to-array and array-to-XML related operations skills, the need for friends can refer to the following
In this paper, we describe the mutual transformation of XML and Arrays in PHP. Share to everyone for your reference, as follows:
The array is converted 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 ();}
XML Conversions to arrays:
function Xmltoarr ($path) { $xmlfile = file_get_contents ($path);//Extract the contents of an XML document to a variable in a string format $ob = Simplexml_load_ String ($xmlfile),//Convert the string to a variable $json = Json_encode ($OB),//Convert the object to a JSON-formatted string $configData = Json_decode ($json, true)//Convert the JSON-formatted string to array print_r ($configData);}