public static function to_xml($data = null, $xml = null, $basenode = 'xml') { // turn off compatibility mode as simple xml throws a wobbly if you don't. if (@ini_get('zend.ze1_compatibility_mode') == 1) { @ini_set('zend.ze1_compatibility_mode', 0); } if ($xml === null) { $xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><{$basenode} />"); } // Force it to be something useful if (!is_array($data) && !is_object($data)) { $data = (array) $data; } foreach ($data as $key => $value) { // no numeric keys in our xml please! if (is_numeric($key)) { // make string key... $key = mgm_singular($basenode) != $basenode ? mgm_singular($basenode) : 'item'; } // replace anything not alpha numeric $key = preg_replace('/[^a-z_\\-0-9]/i', '', $key); $key = preg_replace('/^[0-9]{1,}/i', '', $key); // lower $key = strtolower($key); // if there is another array found recrusively call this function if (is_array($value) || is_object($value)) { $node = $xml->addChild($key); // recrusive call. mgm_format::to_xml($value, $node, $key); } else { // add single node. $value = htmlspecialchars(html_entity_decode($value, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, "UTF-8"); $xml->addChild($key, $value); } } // as xml return $xml->asXML(); }