public static function collapse(&$data, $plural, $singular) { if (!isset($data[$plural])) { return; } if (!isset($data[$plural][$singular])) { unset($data[$plural]); return; } $data[$plural] = $data[$plural][$singular]; // the xml2array function behaves slightly differently if a node has one or multiple children // so we need to check if the result of this operation is an associative array (when it's a single item) // and if so, we nest it in an array if (XMLHelper::isAssoc($data[$plural])) { $data[$plural] = array($data[$plural]); } }
/** * The main function for converting to an XML document. * Pass in a multi dimensional array and this recursively loops through and builds up an XML document. * * @param array $data * @param string $rootNodeName - what you want the root node to be - defaults to data. * @param SimpleXMLElement $xml - should only be used recursively * @return string XML */ public static function toXML($data, $rootNodeName = 'ResultSet', &$xml = null) { // 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 (is_null($xml)) { $xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><{$rootNodeName}/>"); } // loop through the data passed in. foreach ($data as $key => $value) { // no numeric keys in our xml please! $numeric = 0; if (is_numeric($key)) { $numeric = 1; $key = $rootNodeName; } // 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)) { $node = XMLHelper::isAssoc($value) || $numeric ? $xml->addChild($key) : $xml; // recrusive call. if ($numeric) { $key = 'anon'; } XMLHelper::toXml($value, $key, $node); } else { // add single node. $value = htmlentities($value); $xml->addChild($key, $value); } } // pass back as XML return $xml->asXML(); }