{"id":214,"date":"2013-08-07T10:09:32","date_gmt":"2013-08-07T02:09:32","guid":{"rendered":"http:\/\/www.zyuns.com\/?p=214"},"modified":"2015-02-15T20:49:41","modified_gmt":"2015-02-15T12:49:41","slug":"xml2array-convert-xml-to-array-in-php","status":"publish","type":"post","link":"https:\/\/www.siediyer.cn\/?p=214","title":{"rendered":"XML2Array: Convert XML to Array in PHP"},"content":{"rendered":"<h1>XML2Array: Convert XML to Array in PHP<\/h1>\n<p><strong>XML2Array<\/strong> is a class to convert XML to an array in PHP. It returns an array which can be converted back to XML using the <a href=\"http:\/\/www.lalit.org\/lab\/convert-php-array-to-xml-with-attributes\" target=\"_blank\">Array2XML<\/a> class.<\/p>\n<p>&nbsp;<\/p>\n<p>It can take a string XML as input or an object of type <code>DOMDocument<\/code> .<\/p>\n<h3>Conventions<\/h3>\n<ul>\n<li>attributes stored as key value pairs under <code>['tag_name']['@attributes']<\/code><\/li>\n<li>CDATA nodes are stored under <code>['tag_name']['@cdata']<\/code><\/li>\n<li>In case a node has attributes, the value will be stored in <code>['tag_name']['@value']<\/code><\/li>\n<\/ul>\n<h3>Usage<\/h3>\n<p>The usage is pretty simple. You have to include the class file in your code and call the following function.<\/p>\n<p>Php\u4ee3\u7801:<\/p>\n<pre class=\"wrap:true lang:default decode:true \">$array = XML2Array::createArray($xml);\nprint_r($array);<\/pre>\n<p>&nbsp;<\/p>\n<p>Important thing to note is that the <code>$array<\/code> returned can be converted back to XML using the <a href=\"http:\/\/www.lalit.org\/lab\/convert-php-array-to-xml-with-attributes\" target=\"_blank\">Array2XML<\/a> class.<\/p>\n<p>&nbsp;<\/p>\n<h3>Example<\/h3>\n<p>The Following XML:<\/p>\n<p>Xml\u4ee3\u7801<\/p>\n<pre class=\"wrap:true lang:default decode:true \">&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;movies type=\"documentary\"&gt;\n  &lt;movie&gt;\n    &lt;title&gt;PHP: Behind the Parser&lt;\/title&gt;\n    &lt;characters&gt;\n      &lt;character&gt;\n        &lt;name&gt;Ms. Coder&lt;\/name&gt;\n        &lt;actor&gt;Onlivia Actora&lt;\/actor&gt;\n      &lt;\/character&gt;\n      &lt;character&gt;\n        &lt;name&gt;Mr. Coder&lt;\/name&gt;\n        &lt;actor&gt;El Act\u00d3r&lt;\/actor&gt;\n      &lt;\/character&gt;\n    &lt;\/characters&gt;\n    &lt;plot&gt;&lt;![CDATA[So, this language. It's like, a programming language. Or is it a scripting language?\nAll is revealed in this thrilling horror spoof of a documentary.]]&gt;&lt;\/plot&gt;\n    &lt;great-lines&gt;\n      &lt;line&gt;PHP solves all my web problems&lt;\/line&gt;\n    &lt;\/great-lines&gt;\n    &lt;rating type=\"thumbs\"&gt;7&lt;\/rating&gt;\n    &lt;rating type=\"stars\"&gt;5&lt;\/rating&gt;\n  &lt;\/movie&gt;\n&lt;\/movies&gt;<\/pre>\n<p>&nbsp;<\/p>\n<p>will generate the following output:<\/p>\n<p>Php\u4ee3\u7801:<\/p>\n<pre class=\"wrap:true lang:default decode:true \">array (\n    'movies' =&gt; array (\n        'movie' =&gt; array (\n            'title' =&gt; 'PHP: Behind the Parser',\n            'characters' =&gt; array (\n                'character' =&gt; array (\n                    0 =&gt; array (\n                        'name' =&gt; 'Ms. Coder',\n                        'actor' =&gt; 'Onlivia Actora',\n                    ),\n                    1 =&gt; array (\n                        'name' =&gt; 'Mr. Coder',\n                        'actor' =&gt; 'El Act\u00d3r',\n                    ),\n                ),\n            ),\n            'plot' =&gt; array (\n                '@cdata' =&gt; 'So, this language. It's like, a programming language. Or is it a scripting language?\nAll is revealed in this thrilling horror spoof of a documentary.',\n            ),\n            'great-lines' =&gt; array (\n                'line' =&gt; 'PHP solves all my web problems',\n            ),\n            'rating' =&gt; array (\n                0 =&gt; array (\n                    '@value' =&gt; '7',\n                    '@attributes' =&gt; array (\n                        'type' =&gt; 'thumbs',\n                    ),\n                ),\n                1 =&gt; array (\n                    '@value' =&gt; '5',\n                    '@attributes' =&gt; array (\n                        'type' =&gt; 'stars',\n                    ),\n                ),\n            ),\n        ),\n        '@attributes' =&gt; array (\n            'type' =&gt; 'documentary',\n        ),\n    ),\n)<\/pre>\n<p>&nbsp;<\/p>\n<h3>Download (v0.2, 04 Mar, 2012)<\/h3>\n<p>The code is released under Apache License 2.0<\/p>\n<p><a href=\"http:\/\/www.lalit.org\/wordpress\/wp-content\/uploads\/2011\/07\/XML2Array.txt?ver=0.2\" target=\"_blank\">Plain text PHP source<\/a> | <a href=\"http:\/\/www.lalit.org\/wordpress\/wp-content\/uploads\/2011\/07\/XML2Array.html?ver=0.2\" target=\"_blank\">Formatted PHP source<\/a><\/p>\n<p>&nbsp;<\/p>\n<p>\u6765\u6e90\uff1a <a href=\"http:\/\/www.lalit.org\/lab\/convert-xml-to-array-in-php-xml2array\/\" target=\"_blank\">http:\/\/www.lalit.org\/lab\/convert-xml-to-array-in-php-xml2array\/<\/a><\/p>\n<p>&nbsp;<\/p>\n<p>\u6e90\u7801\uff1a<\/p>\n<p>Php\u4ee3\u7801:<\/p>\n<pre class=\"wrap:true lang:default decode:true \">&lt;?php\n\/**\n * XML2Array: A class to convert XML to array in PHP\n * It returns the array which can be converted back to XML using the Array2XML script\n * It takes an XML string or a DOMDocument object as an input.\n *\n * See Array2XML: http:\/\/www.lalit.org\/lab\/convert-php-array-to-xml-with-attributes\n *\n * Author : Lalit Patel\n * Website: http:\/\/www.lalit.org\/lab\/convert-xml-to-array-in-php-xml2array\n * License: Apache License 2.0\n *          http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * Version: 0.1 (07 Dec 2011)\n * Version: 0.2 (04 Mar 2012)\n * \t\t\tFixed typo 'DomDocument' to 'DOMDocument'\n *\n * Usage:\n *       $array = XML2Array::createArray($xml);\n *\/\n\nclass XML2Array {\n\n    private static $xml = null;\n\tprivate static $encoding = 'UTF-8';\n\n    \/**\n     * Initialize the root XML node [optional]\n     * @param $version\n     * @param $encoding\n     * @param $format_output\n     *\/\n    public static function init($version = '1.0', $encoding = 'UTF-8', $format_output = true) {\n        self::$xml = new DOMDocument($version, $encoding);\n        self::$xml-&gt;formatOutput = $format_output;\n\t\tself::$encoding = $encoding;\n    }\n\n    \/**\n     * Convert an XML to Array\n     * @param string $node_name - name of the root node to be converted\n     * @param array $arr - aray to be converterd\n     * @return DOMDocument\n     *\/\n    public static function &amp;createArray($input_xml) {\n        $xml = self::getXMLRoot();\n\t\tif(is_string($input_xml)) {\n\t\t\t$parsed = $xml-&gt;loadXML($input_xml);\n\t\t\tif(!$parsed) {\n\t\t\t\tthrow new Exception('[XML2Array] Error parsing the XML string.');\n\t\t\t}\n\t\t} else {\n\t\t\tif(get_class($input_xml) != 'DOMDocument') {\n\t\t\t\tthrow new Exception('[XML2Array] The input XML object should be of type: DOMDocument.');\n\t\t\t}\n\t\t\t$xml = self::$xml = $input_xml;\n\t\t}\n\t\t$array[$xml-&gt;documentElement-&gt;tagName] = self::convert($xml-&gt;documentElement);\n        self::$xml = null;    \/\/ clear the xml node in the class for 2nd time use.\n        return $array;\n    }\n\n    \/**\n     * Convert an Array to XML\n     * @param mixed $node - XML as a string or as an object of DOMDocument\n     * @return mixed\n     *\/\n    private static function &amp;convert($node) {\n\t\t$output = array();\n\n\t\tswitch ($node-&gt;nodeType) {\n\t\t\tcase XML_CDATA_SECTION_NODE:\n\t\t\t\t$output['@cdata'] = trim($node-&gt;textContent);\n\t\t\t\tbreak;\n\n\t\t\tcase XML_TEXT_NODE:\n\t\t\t\t$output = trim($node-&gt;textContent);\n\t\t\t\tbreak;\n\n\t\t\tcase XML_ELEMENT_NODE:\n\n\t\t\t\t\/\/ for each child node, call the covert function recursively\n\t\t\t\tfor ($i=0, $m=$node-&gt;childNodes-&gt;length; $i&lt;$m; $i++) {\n\t\t\t\t\t$child = $node-&gt;childNodes-&gt;item($i);\n\t\t\t\t\t$v = self::convert($child);\n\t\t\t\t\tif(isset($child-&gt;tagName)) {\n\t\t\t\t\t\t$t = $child-&gt;tagName;\n\n\t\t\t\t\t\t\/\/ assume more nodes of same kind are coming\n\t\t\t\t\t\tif(!isset($output[$t])) {\n\t\t\t\t\t\t\t$output[$t] = array();\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$output[$t][] = $v;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t\/\/check if it is not an empty text node\n\t\t\t\t\t\tif($v !== '') {\n\t\t\t\t\t\t\t$output = $v;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(is_array($output)) {\n\t\t\t\t\t\/\/ if only one node of its kind, assign it directly instead if array($value);\n\t\t\t\t\tforeach ($output as $t =&gt; $v) {\n\t\t\t\t\t\tif(is_array($v) &amp;&amp; count($v)==1) {\n\t\t\t\t\t\t\t$output[$t] = $v[0];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif(empty($output)) {\n\t\t\t\t\t\t\/\/for empty nodes\n\t\t\t\t\t\t$output = '';\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/ loop through the attributes and collect them\n\t\t\t\tif($node-&gt;attributes-&gt;length) {\n\t\t\t\t\t$a = array();\n\t\t\t\t\tforeach($node-&gt;attributes as $attrName =&gt; $attrNode) {\n\t\t\t\t\t\t$a[$attrName] = (string) $attrNode-&gt;value;\n\t\t\t\t\t}\n\t\t\t\t\t\/\/ if its an leaf node, store the value in @value instead of directly storing it.\n\t\t\t\t\tif(!is_array($output)) {\n\t\t\t\t\t\t$output = array('@value' =&gt; $output);\n\t\t\t\t\t}\n\t\t\t\t\t$output['@attributes'] = $a;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t\treturn $output;\n    }\n\n    \/*\n     * Get the root XML node, if there isn't one, create it.\n     *\/\n    private static function getXMLRoot(){\n        if(empty(self::$xml)) {\n            self::init();\n        }\n        return self::$xml;\n    }\n}\n?&gt;<\/pre>\n<p>&nbsp;<\/p>\n<h1>Array2XML: convert PHP Array to XML (with attributes and CDATA)<\/h1>\n<p>&nbsp;<\/p>\n<p><strong>Array2XML<\/strong> is a class to convert an array in PHP to XML. It allows you to parse a multidimensional array into XML including attributes unlike other scripts available on the internet. It returns the XML in form of <a href=\"http:\/\/www.php.net\/manual\/en\/class.domdocument.php\" target=\"_blank\">DOMDocument<\/a> object for further manipulation.<\/p>\n<p>&nbsp;<\/p>\n<p>This library is very helpful when you know the scheme before hand and you have to generate an XML for it using dynamic values from the database.<\/p>\n<p>&nbsp;<\/p>\n<p>The resulting XML can be converted back to an Array using the <a href=\"http:\/\/www.lalit.org\/lab\/convert-xml-to-array-in-php-xml2array\">XML2Array<\/a> class.<\/p>\n<h3>Usage<\/h3>\n<p>The usage is pretty simple. You have to include the class file in your code and call the following function.<\/p>\n<p>Php\u4ee3\u7801<\/p>\n<pre class=\"wrap:true lang:default decode:true \">$xml = Array2XML::createXML('root_node_name', $php_array);\necho $xml-&gt;saveXML();<\/pre>\n<p>&nbsp;<\/p>\n<p>Important thing to note is that the <code>$xml<\/code> object returned is of type <code>DOMDocument<\/code> and hence you can perform further operations on it.<\/p>\n<p>&nbsp;<\/p>\n<p>Optionally you can also set the version of XML and encoding by calling the <code>Array2XML::init()<\/code> function before calling the <code>Array2XML::createXML()<\/code> function.<\/p>\n<p>Php\u4ee3\u7801:<\/p>\n<pre class=\"wrap:true lang:default decode:true \">Array2XML::init($version \/* ='1.0' *\/, $encoding \/* ='UTF-8' *\/);<\/pre>\n<p>&nbsp;<\/p>\n<p>It throws exception if the tag name or attribute name has illegal chars as per <a href=\"http:\/\/www.w3.org\/TR\/xml\/#sec-common-syn\" target=\"_blank\">W3C spec<\/a> .<\/p>\n<h3>Array Structure conventions<\/h3>\n<p>The array passed to the <code>Array2XML::createXML()<\/code> function follows few conventions, which are quite literal and easy to learn\/use. The examples below demonstrate their usage<\/p>\n<p>&nbsp;<\/p>\n<p><strong>1. Empty Nodes:<\/strong> Following will create an empty node.<\/p>\n<p>Php\u4ee3\u7801:<\/p>\n<pre class=\"wrap:true lang:default decode:true \">$books = array();  \/\/ or\n$books = null;  \/\/ or\n$books = '';\n$xml = Array2XML::createXML('books', $books);\n\n\/\/ all three cases above create &lt;books\/&gt;<\/pre>\n<p>&nbsp;<\/p>\n<p><strong>2. Attributes:<\/strong> Attributes can be added to any node by having a <code>@attributes<\/code> key in the array<\/p>\n<p>Php\u4ee3\u7801:<\/p>\n<pre class=\"wrap:true lang:default decode:true \">$books = array(\n        '@attributes' =&gt; array(\n            'type' =&gt; 'fiction',\n            'year' =&gt; 2011,\n            'bestsellers' =&gt; true\n        )\n    );\n$xml = Array2XML::createXML('books', $books);\n\n\/\/ creates &lt;books type=\"fiction\" year=\"2011\" bestsellers=\"true\"\/&gt;<\/pre>\n<p>&nbsp;<\/p>\n<p><strong>3. Node Value:<\/strong> For nodes without attributes, value can be assigned directly, else we need to have a <code>@value<\/code> key in the array. Following examples will make it clear<\/p>\n<p>Php\u4ee3\u7801:<\/p>\n<pre class=\"wrap:true lang:default decode:true \">$books = 1984;  \/\/ or\n    $books = array(\n        '@value' = 1984\n    );\n    \/\/ creates &lt;books&gt;1984&lt;\/books&gt;\n\n    $books = array(\n        '@attributes' =&gt; array(\n            'type' =&gt; 'fiction'\n        ),\n        '@value' = 1984\n    );\n    \/\/ creates &lt;books type=\"fiction\"&gt;1984&lt;\/books&gt;\n\n    $books = array(\n        '@attributes' =&gt; array(\n            'type' =&gt; 'fiction'\n        ),\n        'book' =&gt; 1984\n    );\n    \/* creates\n    &lt;books type=\"fiction\"&gt;\n      &lt;book&gt;1984&lt;\/book&gt;\n    &lt;\/books&gt;\n    *\/\n\n    $books = array(\n        '@attributes' =&gt; array(\n            'type' =&gt; 'fiction'\n        ),\n        'book'=&gt; array('1984','Foundation','Stranger in a Strange Land')\n    );\n    \/* creates\n    &lt;books type=\"fiction\"&gt;\n      &lt;book&gt;1984&lt;\/book&gt;\n      &lt;book&gt;Foundation&lt;\/book&gt;\n      &lt;book&gt;Stranger in a Strange Land&lt;\/book&gt;\n    &lt;\/books&gt;\n    *\/<\/pre>\n<p>&nbsp;<\/p>\n<p><strong>4. Complex XML:<\/strong> Following example clarifies most of the usage of the library<\/p>\n<p>Php\u4ee3\u7801:<\/p>\n<pre class=\"wrap:true lang:default decode:true \">$books = array(\n        '@attributes' =&gt; array(\n            'type' =&gt; 'fiction'\n        ),\n        'book' =&gt; array(\n            array(\n                '@attributes' =&gt; array(\n                    'author' =&gt; 'George Orwell'\n                ),\n                'title' =&gt; '1984'\n            ),\n            array(\n                '@attributes' =&gt; array(\n                    'author' =&gt; 'Isaac Asimov'\n                ),\n                'title' =&gt; array('@cdata'=&gt;'Foundation'),\n                'price' =&gt; '$15.61'\n            ),\n            array(\n                '@attributes' =&gt; array(\n                    'author' =&gt; 'Robert A Heinlein'\n                ),\n                'title' =&gt;  array('@cdata'=&gt;'Stranger in a Strange Land'),\n                'price' =&gt; array(\n                    '@attributes' =&gt; array(\n                        'discount' =&gt; '10%'\n                    ),\n                    '@value' =&gt; '$18.00'\n                )\n            )\n        )\n    );\n    \/* creates\n    &lt;books type=\"fiction\"&gt;\n      &lt;book author=\"George Orwell\"&gt;\n        &lt;title&gt;1984&lt;\/title&gt;\n      &lt;\/book&gt;\n      &lt;book author=\"Isaac Asimov\"&gt;\n        &lt;title&gt;&lt;![CDATA[Foundation]]&gt;&lt;\/title&gt;\n        &lt;price&gt;$15.61&lt;\/price&gt;\n      &lt;\/book&gt;\n      &lt;book author=\"Robert A Heinlein\"&gt;\n        &lt;title&gt;&lt;![CDATA[Stranger in a Strange Land]]&lt;\/title&gt;\n        &lt;price discount=\"10%\"&gt;$18.00&lt;\/price&gt;\n      &lt;\/book&gt;\n    &lt;\/books&gt;\n    *\/<\/pre>\n<p>&nbsp;<\/p>\n<h3>Detailed Example<\/h3>\n<p>You can see a much more detailed example <a href=\"http:\/\/www.lalit.org\/wordpress\/wp-content\/uploads\/2011\/07\/array2xml_example.html?ver=0.8\">here<\/a> .<\/p>\n<h3>Download (v0.8, 2 May, 2012)<\/h3>\n<p>The code is released under Apache License 2.0<\/p>\n<p><a href=\"http:\/\/www.lalit.org\/wordpress\/wp-content\/uploads\/2011\/07\/Array2XML.txt?ver=0.8\" target=\"_blank\">Plaint text PHP source<\/a> | <a href=\"http:\/\/www.lalit.org\/wordpress\/wp-content\/uploads\/2011\/07\/Array2XML.html?ver=0.8\" target=\"_blank\">Formatted PHP source<\/a><\/p>\n<p>&nbsp;<\/p>\n<p>\u6765\u6e90\uff1a <a href=\"http:\/\/www.lalit.org\/lab\/convert-php-array-to-xml-with-attributes\/\" target=\"_blank\">http:\/\/www.lalit.org\/lab\/convert-php-array-to-xml-with-attributes\/<\/a><\/p>\n<p>&nbsp;<\/p>\n<p>\u6e90\u7801\uff1a<\/p>\n<pre class=\"wrap:true lang:default decode:true \">&lt;?php\n\/**\n * Array2XML: A class to convert array in PHP to XML\n * It also takes into account attributes names unlike SimpleXML in PHP\n * It returns the XML in form of DOMDocument class for further manipulation.\n * It throws exception if the tag name or attribute name has illegal chars.\n *\n * Author : Lalit Patel\n * Website: http:\/\/www.lalit.org\/lab\/convert-php-array-to-xml-with-attributes\n * License: Apache License 2.0\n *          http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * Version: 0.1 (10 July 2011)\n * Version: 0.2 (16 August 2011)\n *          - replaced htmlentities() with htmlspecialchars() (Thanks to Liel Dulev)\n *          - fixed a edge case where root node has a false\/null\/0 value. (Thanks to Liel Dulev)\n * Version: 0.3 (22 August 2011)\n *          - fixed tag sanitize regex which didn't allow tagnames with single character.\n * Version: 0.4 (18 September 2011)\n *          - Added support for CDATA section using @cdata instead of @value.\n * Version: 0.5 (07 December 2011)\n *          - Changed logic to check numeric array indices not starting from 0.\n * Version: 0.6 (04 March 2012)\n *          - Code now doesn't @cdata to be placed in an empty array\n * Version: 0.7 (24 March 2012)\n *          - Reverted to version 0.5\n * Version: 0.8 (02 May 2012)\n *          - Removed htmlspecialchars() before adding to text node or attributes.\n *\n * Usage:\n *       $xml = Array2XML::createXML('root_node_name', $php_array);\n *       echo $xml-&gt;saveXML();\n *\/\n\nclass Array2XML {\n\n    private static $xml = null;\n\tprivate static $encoding = 'UTF-8';\n\n    \/**\n     * Initialize the root XML node [optional]\n     * @param $version\n     * @param $encoding\n     * @param $format_output\n     *\/\n    public static function init($version = '1.0', $encoding = 'UTF-8', $format_output = true) {\n        self::$xml = new DomDocument($version, $encoding);\n        self::$xml-&gt;formatOutput = $format_output;\n\t\tself::$encoding = $encoding;\n    }\n\n    \/**\n     * Convert an Array to XML\n     * @param string $node_name - name of the root node to be converted\n     * @param array $arr - aray to be converterd\n     * @return DomDocument\n     *\/\n    public static function &amp;createXML($node_name, $arr=array()) {\n        $xml = self::getXMLRoot();\n        $xml-&gt;appendChild(self::convert($node_name, $arr));\n\n        self::$xml = null;    \/\/ clear the xml node in the class for 2nd time use.\n        return $xml;\n    }\n\n    \/**\n     * Convert an Array to XML\n     * @param string $node_name - name of the root node to be converted\n     * @param array $arr - aray to be converterd\n     * @return DOMNode\n     *\/\n    private static function &amp;convert($node_name, $arr=array()) {\n\n        \/\/print_arr($node_name);\n        $xml = self::getXMLRoot();\n        $node = $xml-&gt;createElement($node_name);\n\n        if(is_array($arr)){\n            \/\/ get the attributes first.;\n            if(isset($arr['@attributes'])) {\n                foreach($arr['@attributes'] as $key =&gt; $value) {\n                    if(!self::isValidTagName($key)) {\n                        throw new Exception('[Array2XML] Illegal character in attribute name. attribute: '.$key.' in node: '.$node_name);\n                    }\n                    $node-&gt;setAttribute($key, self::bool2str($value));\n                }\n                unset($arr['@attributes']); \/\/remove the key from the array once done.\n            }\n\n            \/\/ check if it has a value stored in @value, if yes store the value and return\n            \/\/ else check if its directly stored as string\n            if(isset($arr['@value'])) {\n                $node-&gt;appendChild($xml-&gt;createTextNode(self::bool2str($arr['@value'])));\n                unset($arr['@value']);    \/\/remove the key from the array once done.\n                \/\/return from recursion, as a note with value cannot have child nodes.\n                return $node;\n            } else if(isset($arr['@cdata'])) {\n                $node-&gt;appendChild($xml-&gt;createCDATASection(self::bool2str($arr['@cdata'])));\n                unset($arr['@cdata']);    \/\/remove the key from the array once done.\n                \/\/return from recursion, as a note with cdata cannot have child nodes.\n                return $node;\n            }\n        }\n\n        \/\/create subnodes using recursion\n        if(is_array($arr)){\n            \/\/ recurse to get the node for that key\n            foreach($arr as $key=&gt;$value){\n                if(!self::isValidTagName($key)) {\n                    throw new Exception('[Array2XML] Illegal character in tag name. tag: '.$key.' in node: '.$node_name);\n                }\n                if(is_array($value) &amp;&amp; is_numeric(key($value))) {\n                    \/\/ MORE THAN ONE NODE OF ITS KIND;\n                    \/\/ if the new array is numeric index, means it is array of nodes of the same kind\n                    \/\/ it should follow the parent key name\n                    foreach($value as $k=&gt;$v){\n                        $node-&gt;appendChild(self::convert($key, $v));\n                    }\n                } else {\n                    \/\/ ONLY ONE NODE OF ITS KIND\n                    $node-&gt;appendChild(self::convert($key, $value));\n                }\n                unset($arr[$key]); \/\/remove the key from the array once done.\n            }\n        }\n\n        \/\/ after we are done with all the keys in the array (if it is one)\n        \/\/ we check if it has any text value, if yes, append it.\n        if(!is_array($arr)) {\n            $node-&gt;appendChild($xml-&gt;createTextNode(self::bool2str($arr)));\n        }\n\n        return $node;\n    }\n\n    \/*\n     * Get the root XML node, if there isn't one, create it.\n     *\/\n    private static function getXMLRoot(){\n        if(empty(self::$xml)) {\n            self::init();\n        }\n        return self::$xml;\n    }\n\n    \/*\n     * Get string representation of boolean value\n     *\/\n    private static function bool2str($v){\n        \/\/convert boolean to text value.\n        $v = $v === true ? 'true' : $v;\n        $v = $v === false ? 'false' : $v;\n        return $v;\n    }\n\n    \/*\n     * Check if the tag name or attribute name contains illegal characters\n     * Ref: http:\/\/www.w3.org\/TR\/xml\/#sec-common-syn\n     *\/\n    private static function isValidTagName($tag){\n        $pattern = '\/^[a-z_]+[a-z0-9:-._]*[^:]*$\/i';\n        return preg_match($pattern, $tag, $matches) &amp;&amp; $matches[0] == $tag;\n    }\n}\n?&gt;<\/pre>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>XML2Array: Convert XML to Array in PHP XML2Array is a c [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-214","post","type-post","status-publish","format-standard","hentry","category-php"],"_links":{"self":[{"href":"https:\/\/www.siediyer.cn\/index.php?rest_route=\/wp\/v2\/posts\/214","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.siediyer.cn\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.siediyer.cn\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.siediyer.cn\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.siediyer.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=214"}],"version-history":[{"count":1,"href":"https:\/\/www.siediyer.cn\/index.php?rest_route=\/wp\/v2\/posts\/214\/revisions"}],"predecessor-version":[{"id":438,"href":"https:\/\/www.siediyer.cn\/index.php?rest_route=\/wp\/v2\/posts\/214\/revisions\/438"}],"wp:attachment":[{"href":"https:\/\/www.siediyer.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=214"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.siediyer.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=214"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.siediyer.cn\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=214"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}