40 private static $xml = null;
41 private static $encoding =
'UTF-8';
49 public static function init($version =
'1.0', $encoding =
'UTF-8', $format_output =
true)
51 self::$xml = new \DomDocument($version, $encoding);
52 self::$xml->formatOutput = $format_output;
53 self::$encoding = $encoding;
62 public static function &
createXML($node_name, $arr = array(), $namespace = null)
64 $xml = self::getXMLRoot();
65 $xml->appendChild(self::convert($node_name, $arr, $namespace));
77 private static function &convert($node_name, $arr = array(), $xmlns = null)
81 $xml = self::getXMLRoot();
82 $node = $xml->createElement($node_name);
84 if (is_string($xmlns))
86 $node->setAttribute(
"xmlns", $xmlns);
88 elseif (is_array($xmlns))
90 foreach ($xmlns as $k => $v)
92 $node->setAttribute($k, $v);
98 if (isset($arr[
'@attributes']))
100 foreach ($arr[
'@attributes'] as $key => $value)
102 if (!self::isValidTagName($key))
104 $sErrorMessage =
'[Array2XML] Illegal character in attribute name. attribute: ' . $key .
' in node: ' . $node_name;
106 throw new \Exception($sErrorMessage);
108 $node->setAttribute($key, self::bool2str($value));
110 unset($arr[
'@attributes']);
115 if (isset($arr[
'@value']))
117 $node->appendChild($xml->createTextNode(self::bool2str($arr[
'@value'])));
118 unset($arr[
'@value']);
122 else if (isset($arr[
'@cdata']))
124 $node->appendChild($xml->createCDATASection(self::bool2str($arr[
'@cdata'])));
125 unset($arr[
'@cdata']);
135 foreach ($arr as $key => $value)
137 if (!self::isValidTagName($key))
139 $sErrorMessage =
'[Array2XML] Illegal character in tag name. tag: ' . $key .
' in node: ' . $node_name;
141 throw new \Exception($sErrorMessage);
143 if (is_array($value) && is_numeric(key($value)))
148 foreach ($value as $k => $v)
150 $node->appendChild(self::convert($key, $v));
156 $node->appendChild(self::convert($key, $value));
166 $node->appendChild($xml->createTextNode(self::bool2str($arr)));
176 private static function getXMLRoot()
178 if (empty(self::$xml))
189 private static function bool2str($v)
192 $v = $v ===
true ?
'true' : $v;
193 $v = $v ===
false ?
'false' : $v;
202 private static function isValidTagName($tag)
204 $pattern =
'/^[a-z_]+[a-z0-9\:\-\.\_]*[^:]*$/i';
205 return preg_match($pattern, $tag, $matches) && $matches[0] == $tag;
static get($sChannel="default", $sLogRoot="")
static & createXML($node_name, $arr=array(), $namespace=null)
static init($version= '1.0', $encoding= 'UTF-8', $format_output=true)