/** * The main function for converting to an XML document. * Pass in a multi dimensional array and this recrusively loops through and builds up an XML document. * * @static * @param array $data * @param string $rootNodeName - what you want the root node to be - defaultsto data. * @param SimpleXMLElement $xml - should only be used recursively * @return string XML */ public static function toXml($data, $rootNodeName = 'data', &$xml = NULL, $root_attributes = null) { if (is_null($xml)) { $xml = new SimpleXMLElement('<' . $rootNodeName . ' ' . $root_attributes . ' />'); } // loop through the data passed in. foreach ($data as $key => $value) { // if numeric key, assume array of rootNodeName elements if (is_numeric($key)) { $key = $rootNodeName; } // Check if is attribute if ($key == TiendaArrayToXML::attr_arr_string) { // Add attributes to node foreach ($value as $attr_name => $attr_value) { $xml->addAttribute($attr_name, $attr_value); } } else { // delete any char not allowed in XML element names $key = preg_replace('/[^a-z0-9\\-\\_\\.\\]/i', '', $key); // if there is another array found recrusively call this function if (is_array($value)) { // create a new node unless this is an array of elements $node = TiendaArrayToXML::isAssoc($value) ? $xml->addChild($key) : $xml; // recrusive call - pass $key as the new rootNodeName TiendaArrayToXML::toXml($value, $key, $node); } else { // add single node. $value = htmlentities($value); $xml->addChild($key, $value); } } } // pass back as string. or simple xml object if you want! $dom = dom_import_simplexml($xml)->ownerDocument; $dom->formatOutput = true; return $dom->saveXML(); }