"); self::array_to_xml($obj, $simpleElementXml); //for formatting ... $dom = dom_import_simplexml($simpleElementXml)->ownerDocument; $dom->formatOutput = true; return $dom->saveXML(); } /** * Convert array to xml * @param array $data * @param $xml_data */ private static function array_to_xml($data = [], &$xml_data) { foreach ($data as $key => $value) { if (is_array($value) or (is_object($value))) { if (!is_numeric($key)) { $subnode = $xml_data->addChild("$key"); self::array_to_xml($value, $subnode); } else { $subnode = $xml_data->addChild("element"); self::array_to_xml($value, $subnode); } } else { if (is_bool($value)) { $value = $value ? "true" : "false"; } $xml_data->addChild("$key", "$value"); } } } /** * Convert xml to array * @param string $xml * @return mixed * @throws common_exception_Error */ public static function to_array($xml) { $json = json_encode(self::getSimpleXml($xml)); return json_decode($json, true); } /** * @param $xml * @return SimpleXMLElement * @throws common_exception_Error */ public static function getSimpleXml($xml) { libxml_use_internal_errors(true); $xml = simplexml_load_string($xml); if ($xml === false) { $report = []; $errors = libxml_get_errors(); /** @var LibXMLError $error */ foreach ($errors as $error) { $report[] = trim($error->message) . ' [' . $error->line . ']'; } libxml_clear_errors(); throw new common_exception_Error(implode("\n", $report)); } return $xml; } /** * Extract elements from the xml (xpath) with namespace dependency * @param $tagName * @param $xml * @param string $namespace * @return array * @throws common_exception_Error */ public static function extractElements($tagName, $xml, $namespace = '') { $elements = []; $simpleXml = self::getSimpleXml($xml); $ns = ''; if ($namespace) { $simpleXml->registerXPathNamespace('ns', $namespace); $ns = 'ns:'; } $tagName = $ns . $tagName; foreach ($simpleXml->xpath('//' . $tagName) as $item) { $elements [] = current($item); } return $elements; } }