27 private static $xml = null;
28 private static $encoding =
'UTF-8';
36 public static function init($version =
'1.0', $encoding =
'UTF-8', $format_output =
true)
38 self::$xml = new \DOMDocument($version, $encoding);
39 self::$xml->formatOutput = $format_output;
40 self::$encoding = $encoding;
51 $xml = self::getXMLRoot();
52 if (is_string($input_xml))
54 $parsed = $xml->loadXML($input_xml);
57 throw new \Exception(
'[XML2Array] Error parsing the XML string.');
62 if (get_class($input_xml) !=
'DOMDocument')
64 throw new \Exception(
'[XML2Array] The input XML object should be of type: DOMDocument.');
66 $xml = self::$xml = $input_xml;
68 $array[$xml->documentElement->tagName] = self::convert($xml->documentElement);
78 private static function &convert($node)
82 switch ($node->nodeType)
84 case XML_CDATA_SECTION_NODE:
85 $output[
'@cdata'] = trim($node->textContent);
89 $output = trim($node->textContent);
92 case XML_ELEMENT_NODE:
95 for ($i = 0, $m = $node->childNodes->length; $i < $m; $i++)
97 $child = $node->childNodes->item($i);
98 $v = self::convert($child);
99 if (isset($child->tagName))
101 $t = $child->tagName;
104 if (!isset($output[$t]))
106 $output[$t] = array();
120 if (is_array($output))
123 foreach ($output as $t => $v)
125 if (is_array($v) && count($v) == 1)
138 if ($node->attributes->length)
141 foreach ($node->attributes as $attrName => $attrNode)
143 $a[$attrName] = (string) $attrNode->value;
146 if (!is_array($output))
148 $output = array(
'@value' => $output);
150 $output[
'@attributes'] = $a;
161 private static function getXMLRoot()
163 if (empty(self::$xml))
static init($version= '1.0', $encoding= 'UTF-8', $format_output=true)
static & createArray($input_xml)