set_data($data); $xmlObject = new \SimpleXMLElement(''); $this->array_to_xml($data, $xmlObject); return $xmlObject->asXML(); } /** * Convert xml to php data * * @param string $string * @return object */ public function unserialize($string) { $xml = \simplexml_load_string($string); $json = json_encode($xml); $object = json_decode($json); return $object; } /** * Recursively generate xml from an array or object * * @param array|object $array * @param \SimpleXMLElement $xmlObject */ private function array_to_xml($array, \SimpleXMLElement &$xmlObject) { foreach($array as $key => $val) { $key = $this->fix_xml_key($key); if ( ! is_scalar($val)) { $subnode = $xmlObject->addChild($key); $this->array_to_xml($val, $subnode); } else { $xmlObject->addChild($key, \htmlspecialchars($val, ENT_XML1, 'UTF-8')); } } } /** * Make an invalid xml key more valid * * @param string $key * @return string */ private function fix_xml_key($key) { if (is_numeric($key)) { $key = "item_{$key}"; } return preg_replace('`[^a-zA-Z0-9_:]`', '_', $key); } } // End of Type/XML.php