<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>
<title>Comments on snippet: 'Convert PHP Array to XML or Simple XML Object if you wish'</title>
<link>http://snipplr.com</link>
<description>Snipplr comments feed'</description>
<language>en-us</language>
<pubDate>Tue, 14 Feb 2012 03:26:34 GMT</pubDate>
<item>
<title>seanvillanigmailcom said on 3/18/11</title>
<link>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</link>
<description><![CDATA[ This is a nice little method. I've added some code to automatically ad cdata if it's not a number:

<code>
               // add single node.
                $value = htmlentities($value);
               
                //add cdata if not numeric
                if (!is_numeric($value))
                {
                    $dom = dom_import_simplexml($xml);
                    $value = $dom->ownerDocument->createCDATASection($value);
                    $dom->appendChild($value);
                }

                // add child
                $xml->addChild($key, $value);
</code> ]]></description>
<pubDate>Fri, 18 Mar 2011 04:23:32 GMT</pubDate>
<guid>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</guid>
</item>
<item>
<title>OmerHassan said on 12/3/10</title>
<link>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</link>
<description><![CDATA[ Hi,

I just wrote a simple class to convert array to DOMDocument. Here it is: http://code.google.com/p/array-to-domdocument/. ]]></description>
<pubDate>Fri, 03 Dec 2010 21:52:25 GMT</pubDate>
<guid>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</guid>
</item>
<item>
<title>nickfellowsgmailcom said on 11/5/10</title>
<link>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</link>
<description><![CDATA[ Some older versions of PHP the compiled in SimpleXML library does not have the "addChild" function

Here's my version that has a fallback method if you are not in a position to upgrade your PHP and need this to work fast.

class ArrayToXML
{
    /**
     * The main function for converting to an XML document.
     * Pass in a multi dimensional array and this recrusively loops through and builds up http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/an XML document.
     *
     * @param array $data
     * @param string $rootNodeName - what you want the root node to be - defaultsto data.
     * @param SimpleXMLElement $xml - should only be used recursively
     * @return string XML
     */
    public static function toXML( $data, $rootNodeName = 'ResultSet', &amp;$xml=null ) {

        // turn off compatibility mode as simple xml throws a wobbly if you don't.
        if ( ini_get('zend.ze1_compatibility_mode') == 1 ) ini_set ( 'zend.ze1_compatibility_mode', 0 );
        if ( is_null( $xml ) ) $xml = simplexml_load_string( "" );

        // loop through the data passed in.
        foreach( $data as $key => $value ) {

            // no numeric keys in our xml please!
            if ( is_numeric( $key ) ) {
                $numeric = 1;
                $key = $rootNodeName;
            }

            // delete any char not allowed in XML element names
            $key = preg_replace('/[^a-z0-9\-\_\.\:]/i', '', $key);

            // if there is another array found recursively call this function
            if ( is_array( $value ) ) {

            	if ( ArrayToXML::is_assoc( $value ) || $numeric ) {

					// older SimplXMLElement Libraries do not have the addChild Method
					if (method_exists('SimpleXMLElement','addChild'))
					{
						$node = $xml->addChild( $key );
					}
					else
					{// alternative / dirty method for adding a child
				     $domchild = new DOMElement($key,$value);
    	             $dom= new DOMDocument;
         		     $dom = dom_import_simplexml($xml);
                	 $dom->appendChild($domchild);
                	 $xml = simplexml_import_dom($dom);
	 				 $node = $xml;
					}

				}else{
					$node =$xml;
				}

                // recrusive call.
                if ( $numeric ) $key = 'anon';
                ArrayToXML::toXml( $value, $key, $node );
            } else {

					// older SimplXMLElement Libraries do not have the addChild Method
					if (method_exists('SimpleXMLElement','addChild'))
					{
						$xml->addChild( $key );
					}
					else
					{	// alternative / dirty method for adding a child
					     $domchild = new DOMElement($key,$value);
	    	             $dom= new DOMDocument;
	         		     $dom = dom_import_simplexml($xml);
	                	 $dom->appendChild($domchild);
	                	 $xml = simplexml_import_dom($dom);
					}
            }
        }

        // pass back as XML
        return $xml->asXML();

    // if you want the XML to be formatted, use the below instead to return the XML
        //$doc = new DOMDocument('1.0');
        //$doc->preserveWhiteSpace = false;
        //$doc->loadXML( $xml->asXML() );
        //$doc->formatOutput = true;
        //return $doc->saveXML();
    }


    /**
     * Convert an XML document to a multi dimensional array
     * Pass in an XML document (or SimpleXMLElement object) and this recrusively loops through and builds a representative array
     *
     * @param string $xml - XML document - can optionally be a SimpleXMLElement object
     * @return array ARRAY
     */
    public static function toArray( $xml ) {
        if ( is_string( $xml ) ) $xml = new SimpleXMLElement( $xml );
        $children = $xml->children();
        if ( !$children ) return (string) $xml;
        $arr = array();
        foreach ( $children as $key => $node ) {
            $node = ArrayToXML::toArray( $node );

            // support for 'anon' non-associative arrays
            if ( $key == 'anon' ) $key = count( $arr );

            // if the node is already set, put it into an array
            if ( isset( $arr[$key] ) ) {
                if ( !is_array( $arr[$key] ) || $arr[$key][0] == null ) $arr[$key] = array( $arr[$key] );
                $arr[$key][] = $node;
            } else {
                $arr[$key] = $node;
            }
        }
        return $arr;
    }

    // determine if a variable is an associative array
    public static function is_assoc( $array ) {
        return (is_array($array) &amp;&amp; 0 !== count(array_diff_key($array, array_keys(array_keys($array)))));
    }
} ]]></description>
<pubDate>Fri, 05 Nov 2010 22:44:16 GMT</pubDate>
<guid>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</guid>
</item>
<item>
<title>Pixelmixer said on 9/24/10</title>
<link>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</link>
<description><![CDATA[ heh.... Sorry for the spamming...


` ]]></description>
<pubDate>Fri, 24 Sep 2010 04:41:49 GMT</pubDate>
<guid>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</guid>
</item>
<item>
<title>Pixelmixer said on 9/24/10</title>
<link>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</link>
<description><![CDATA[ `class ArrayToXML
{
    /**
     * The main function for converting to an XML document.
     * Pass in a multi dimensional array and this recrusively loops through and builds up an XML document.
     *
     * @param array $data
     * @param string $rootNodeName - what you want the root node to be - defaultsto data.
     * @param SimpleXMLElement $xml - should only be used recursively
     * @return string XML
     */
    public static function toXML( $data, $rootNodeName = 'ResultSet', &amp;$xml=null ) {

        // turn off compatibility mode as simple xml throws a wobbly if you don't.
        if ( ini_get('zend.ze1_compatibility_mode') == 1 ) ini_set ( 'zend.ze1_compatibility_mode', 0 );
        if ( is_null( $xml ) ) $xml = new SimpleXMLElement('');

        // loop through the data passed in.
        foreach( $data as $key => $value ) {

            // no numeric keys in our xml please!
            if ( is_numeric( $key ) ) {
                $numeric = 1;
                $key = $rootNodeName;
            }

            // delete any char not allowed in XML element names
            $key = preg_replace('/[^a-z0-9\-\_\.\:]/i', '', $key);

			if( is_object( $value ) ) {
				$value = get_object_vars( $value );			
			}
			
            // if there is another array found recrusively call this function
            if ( is_array( $value ) ) {
                $node = ArrayToXML::is_assoc( $value ) || $numeric ? $xml->addChild( $key ) : $xml;

                // recrusive call.
                if ( $numeric ) $key = 'anon';
                ArrayToXML::toXml( $value, $key, $node );
            } else {

                // add single node.
                $value = htmlentities( $value );
                $xml->addChild( $key, $value );
            }
        }

        // pass back as XML
        //return $xml->asXML();

    // if you want the XML to be formatted, use the below instead to return the XML
        $doc = new DOMDocument('1.0');
        $doc->preserveWhiteSpace = false;
        $doc->loadXML( $xml->asXML() );
        $doc->formatOutput = true;
        return $doc->saveXML();
    }


    /**
     * Convert an XML document to a multi dimensional array
     * Pass in an XML document (or SimpleXMLElement object) and this recrusively loops through and builds a representative array
     *
     * @param string $xml - XML document - can optionally be a SimpleXMLElement object
     * @return array ARRAY
     */
    public static function toArray( $xml ) {
        if ( is_string( $xml ) ) $xml = new SimpleXMLElement( $xml );
        $children = $xml->children();
        if ( !$children ) return (string) $xml;
        $arr = array();
        foreach ( $children as $key => $node ) {
            $node = ArrayToXML::toArray( $node );

            // support for 'anon' non-associative arrays
            if ( $key == 'anon' ) $key = count( $arr );

            // if the node is already set, put it into an array
            if ( isset( $arr[$key] ) ) {
                if ( !is_array( $arr[$key] ) || $arr[$key][0] == null ) $arr[$key] = array( $arr[$key] );
                $arr[$key][] = $node;
            } else {
                $arr[$key] = $node;
            }
        }
        return $arr;
    }

    // determine if a variable is an associative array
    public static function is_assoc( $array ) {
        return (is_array($array) &amp;&amp; 0 !== count(array_diff_key($array, array_keys(array_keys($array)))));
    }
}` ]]></description>
<pubDate>Fri, 24 Sep 2010 04:40:58 GMT</pubDate>
<guid>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</guid>
</item>
<item>
<title>Pixelmixer said on 9/24/10</title>
<link>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</link>
<description><![CDATA[ `class ArrayToXML
{
    /**
     * The main function for converting to an XML document.
     * Pass in a multi dimensional array and this recrusively loops through and builds up an XML document.
     *
     * @param array $data
     * @param string $rootNodeName - what you want the root node to be - defaultsto data.
     * @param SimpleXMLElement $xml - should only be used recursively
     * @return string XML
     */
    public static function toXML( $data, $rootNodeName = 'ResultSet', &amp;$xml=null ) {

        // turn off compatibility mode as simple xml throws a wobbly if you don't.
        if ( ini_get('zend.ze1_compatibility_mode') == 1 ) ini_set ( 'zend.ze1_compatibility_mode', 0 );
        if ( is_null( $xml ) ) $xml = new SimpleXMLElement('');

        // loop through the data passed in.
        foreach( $data as $key => $value ) {

            // no numeric keys in our xml please!
            if ( is_numeric( $key ) ) {
                $numeric = 1;
                $key = $rootNodeName;
            }

            // delete any char not allowed in XML element names
            $key = preg_replace('/[^a-z0-9\-\_\.\:]/i', '', $key);

			if( is_object( $value ) ) {
				$value = get_object_vars( $value );			
			}
			
            // if there is another array found recrusively call this function
            if ( is_array( $value ) ) {
                $node = ArrayToXML::is_assoc( $value ) || $numeric ? $xml->addChild( $key ) : $xml;

                // recrusive call.
                if ( $numeric ) $key = 'anon';
                ArrayToXML::toXml( $value, $key, $node );
            } else {

                // add single node.
                $value = htmlentities( $value );
                $xml->addChild( $key, $value );
            }
        }

        // pass back as XML
        //return $xml->asXML();

    // if you want the XML to be formatted, use the below instead to return the XML
        $doc = new DOMDocument('1.0');
        $doc->preserveWhiteSpace = false;
        $doc->loadXML( $xml->asXML() );
        $doc->formatOutput = true;
        return $doc->saveXML();
    }


    /**
     * Convert an XML document to a multi dimensional array
     * Pass in an XML document (or SimpleXMLElement object) and this recrusively loops through and builds a representative array
     *
     * @param string $xml - XML document - can optionally be a SimpleXMLElement object
     * @return array ARRAY
     */
    public static function toArray( $xml ) {
        if ( is_string( $xml ) ) $xml = new SimpleXMLElement( $xml );
        $children = $xml->children();
        if ( !$children ) return (string) $xml;
        $arr = array();
        foreach ( $children as $key => $node ) {
            $node = ArrayToXML::toArray( $node );

            // support for 'anon' non-associative arrays
            if ( $key == 'anon' ) $key = count( $arr );

            // if the node is already set, put it into an array
            if ( isset( $arr[$key] ) ) {
                if ( !is_array( $arr[$key] ) || $arr[$key][0] == null ) $arr[$key] = array( $arr[$key] );
                $arr[$key][] = $node;
            } else {
                $arr[$key] = $node;
            }
        }
        return $arr;
    }

    // determine if a variable is an associative array
    public static function is_assoc( $array ) {
        return (is_array($array) &amp;&amp; 0 !== count(array_diff_key($array, array_keys(array_keys($array)))));
    }
}` ]]></description>
<pubDate>Fri, 24 Sep 2010 04:40:57 GMT</pubDate>
<guid>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</guid>
</item>
<item>
<title>Pixelmixer said on 9/24/10</title>
<link>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</link>
<description><![CDATA[ I've modified @wwwzealdotcom 's code a bit to accept Arrays that can contain a mixture of Arrays and Objects.

<p> ]]></description>
<pubDate>Fri, 24 Sep 2010 04:39:24 GMT</pubDate>
<guid>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</guid>
</item>
<item>
<title>nfreear said on 8/12/10</title>
<link>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</link>
<description><![CDATA[ Hi,
Thank you for the snippets!

I'd like to use this code in a project that will be open-source, probably using the GPL version 2. Is this OK please, djdykes and others?

Many thanks,

Nick ]]></description>
<pubDate>Thu, 12 Aug 2010 23:13:46 GMT</pubDate>
<guid>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</guid>
</item>
<item>
<title>aubiematt said on 10/21/09</title>
<link>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</link>
<description><![CDATA[ Converted this to a CakePHP helper.  Hopefully someone will find this useful.

Save this to 'app/view/helpers/simplexml.php'.

<code> ]]></description>
<pubDate>Wed, 21 Oct 2009 11:56:16 GMT</pubDate>
<guid>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</guid>
</item>
<item>
<title>aubiematt said on 10/21/09</title>
<link>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</link>
<description><![CDATA[ Converted this to a CakePHP helper.  Hopefully someone will find this useful.

Save this to 'app/view/helpers/simplexml.php'.
<code> ]]></description>
<pubDate>Wed, 21 Oct 2009 11:53:34 GMT</pubDate>
<guid>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</guid>
</item>
<item>
<title>lukep said on 9/4/09</title>
<link>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</link>
<description><![CDATA[ Not a fan of Markdown, I have to say.

    $xml = simplexml_load_string(""); ]]></description>
<pubDate>Fri, 04 Sep 2009 22:36:56 GMT</pubDate>
<guid>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</guid>
</item>
<item>
<title>lukep said on 9/4/09</title>
<link>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</link>
<description><![CDATA[ Oops, the line to use is in fact:

`$xml = simplexml_load_string("");`

(this place needs an edit function) ]]></description>
<pubDate>Fri, 04 Sep 2009 22:32:04 GMT</pubDate>
<guid>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</guid>
</item>
<item>
<title>lukep said on 9/4/09</title>
<link>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</link>
<description><![CDATA[ I'm using wwwzealdcom's version of this class, it's extremely useful. However, on my version of PHP (5.2.8 Win32), it seems I have to use the following line instead of the simplexml_load_string("") as in the original post to avoid having FALSE returned instead of a SimpleXMLElement:

`$xml = simplexml_load_string("");` ]]></description>
<pubDate>Fri, 04 Sep 2009 22:30:40 GMT</pubDate>
<guid>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</guid>
</item>
<item>
<title>wwwzealdcom said on 8/30/09</title>
<link>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</link>
<description><![CDATA[ Ok so the above doesn't work with arrays of arrays ... the correct (and hopefully final! :)) toXML with its corresponding toArray is below. Non-associative arrays are labelled as 'anon' as with Perl's XML::Simple.

I've also included a commented-out little snippet at the bottom which you can use if you want formatted XML thats easy to read (SimpleXMLElement::asXML() returns it all on one line).

<pre><code>


class ArrayToXML
{
    /**
     * The main function for converting to an XML document.
     * Pass in a multi dimensional array and this recrusively loops through and builds up an XML document.
     *
     * @param array $data
     * @param string $rootNodeName - what you want the root node to be - defaultsto data.
     * @param SimpleXMLElement $xml - should only be used recursively
     * @return string XML
     */
    public static function toXML( $data, $rootNodeName = 'ResultSet', &amp;$xml=null ) {

        // turn off compatibility mode as simple xml throws a wobbly if you don't.
        if ( ini_get('zend.ze1_compatibility_mode') == 1 ) ini_set ( 'zend.ze1_compatibility_mode', 0 );
        if ( is_null( $xml ) ) $xml = simplexml_load_string( "" );

        // loop through the data passed in.
        foreach( $data as $key => $value ) {

            // no numeric keys in our xml please!
            if ( is_numeric( $key ) ) {
                $numeric = 1;
                $key = $rootNodeName;
            }

            // delete any char not allowed in XML element names
            $key = preg_replace('/[^a-z0-9\-\_\.\:]/i', '', $key);

            // if there is another array found recrusively call this function
            if ( is_array( $value ) ) {
                $node = ArrayToXML::is_assoc( $value ) || $numeric ? $xml->addChild( $key ) : $xml;

                // recrusive call.
                if ( $numeric ) $key = 'anon';
                ArrayToXML::toXml( $value, $key, $node );
            } else {

                // add single node.
                $value = htmlentities( $value );
                $xml->addChild( $key, $value );
            }
        }

        // pass back as XML
        return $xml->asXML();

	// if you want the XML to be formatted, use the below instead to return the XML
        //$doc = new DOMDocument('1.0');
        //$doc->preserveWhiteSpace = false;
        //$doc->loadXML( $xml->asXML() );
        //$doc->formatOutput = true;
        //return $doc->saveXML();
    }


    /**
     * Convert an XML document to a multi dimensional array
     * Pass in an XML document (or SimpleXMLElement object) and this recrusively loops through and builds a representative array
     *
     * @param string $xml - XML document - can optionally be a SimpleXMLElement object
     * @return array ARRAY
     */
    public static function toArray( $xml ) {
        if ( is_string( $xml ) ) $xml = new SimpleXMLElement( $xml );
        $children = $xml->children();
        if ( !$children ) return (string) $xml;
        $arr = array();
        foreach ( $children as $key => $node ) {
            $node = ArrayToXML::toArray( $node );

            // support for 'anon' non-associative arrays
            if ( $key == 'anon' ) $key = count( $arr );

            // if the node is already set, put it into an array
            if ( isset( $arr[$key] ) ) {
                if ( !is_array( $arr[$key] ) || $arr[$key][0] == null ) $arr[$key] = array( $arr[$key] );
                $arr[$key][] = $node;
            } else {
                $arr[$key] = $node;
            }
        }
        return $arr;
    }

    // determine if a variable is an associative array
    public static function isAssoc( $array ) {
        return (is_array($array) &amp;&amp; 0 !== count(array_diff_key($array, array_keys(array_keys($array)))));
    }
}

</code></pre> ]]></description>
<pubDate>Sun, 30 Aug 2009 08:14:44 GMT</pubDate>
<guid>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</guid>
</item>
<item>
<title>wwwzealdcom said on 8/26/09</title>
<link>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</link>
<description><![CDATA[ Another helpful piece of code to add to this class is the reverse of this function which converts XML (or a SimpleXMLElement object) to an array format which can be converted back using the toXML function:

<pre><code>
    public static function toArray( $obj, &amp;$arr = null ){
        if ( is_null( $arr ) ) $arr = array();
        if ( is_string( $obj ) ) $obj = new SimpleXMLElement( $obj );
        $children = $obj->children();
        $executed = false;
        foreach ($children as $elementName => $node){
            if($arr[$elementName]!=null){
                if($arr[$elementName][0]!==null){
                    $i = count($arr[$elementName]);
                    ArrayToXML::toArray($node, $arr[$elementName][$i]);
                }else{
                    $tmp = $arr[$elementName];
                    $arr[$elementName] = array();
                    $arr[$elementName][0] = $tmp;
                    $i = count($arr[$elementName]);
                    ArrayToXML::toArray($node, $arr[$elementName][$i]);
                }
            }else{
                $arr[$elementName] = array();
                ArrayToXML::toArray($node, $arr[$elementName]);
            }
            $executed = true;
        }
        if(!$executed&amp;&amp;$children->getName()==""){
            $arr = (String)$obj;
        }
        return $arr;
    }
</pre></code> ]]></description>
<pubDate>Wed, 26 Aug 2009 09:44:02 GMT</pubDate>
<guid>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</guid>
</item>
<item>
<title>wwwzealdcom said on 8/26/09</title>
<link>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</link>
<description><![CDATA[ Great class with one exception - it doesn't support a common XML structure such as:

<pre><code>

<library>
    <book>
        <authorFirst>Mark</authorFirst>
        <authorLast>Twain</authorLast>
        <title>The Innocents Abroad</title>
    </book>
    <book>
        <authorFirst>Charles</authorFirst>
        <authorLast>Dickens</authorLast>
        <title>Oliver Twist</title>
    </book>
</library>
</code></pre>


The way to represent this in array form would be:

<pre><code>
$library = array(
    book => array(
        array(
            'authorFirst' => 'Mark'
            'authorLast' => 'Twain'
            'title' => 'The Innocents Abroad'
        ),
        array(
            'authorFirst' => 'Charles'
            'authorLast' => 'Dickens'
            'title' => 'Oliver Twist'
        )
    )
);
</code></pre>


However using the current class this would output:

<pre><code>
<library>
    <book>
        <unknownNode_0>
            <authorFirst>Mark</authorFirst>
            <authorLast>Twain</authorLast>
            <title>The Innocents Abroad</title>
        </unknownNode_0>
        <unknownNode_1>
            <authorFirst>Charles</authorFirst>
            <authorLast>Dickens</authorLast>
            <title>Oliver Twist</title>
        </unknownNode_1>
    </book>
</library>
</code></pre>

... which doesn't make a lot of sense.

SO, the class modified to handle the above situation &amp; a non-associative array in a sensible fashion (including above fixes by visual77 and hradek):

<pre><code>
class ArrayToXML
{
    /**
     * The main function for converting to an XML document.
     * Pass in a multi dimensional array and this recrusively loops through and builds up an XML document.
     *
     * @param array $data
     * @param string $rootNodeName - what you want the root node to be - defaultsto data.
     * @param SimpleXMLElement $xml - should only be used recursively
     * @return string XML
     */
    public static function toXml($data, $rootNodeName = 'data', &amp;$xml=null)
    {
        // turn off compatibility mode as simple xml throws a wobbly if you don't.
        if (ini_get('zend.ze1_compatibility_mode') == 1)
        {
            ini_set ('zend.ze1_compatibility_mode', 0);
        }

        if (is_null($xml))
        {
            $xml = simplexml_load_string("");
        }

        // loop through the data passed in.
        foreach($data as $key => $value)
        {
            // if numeric key, assume array of rootNodeName elements
            if (is_numeric($key))
            {
                $key = $rootNodeName;
            }

            // delete any char not allowed in XML element names
            $key = preg_replace('/[^a-z0-9\-\_\.\:]/i', '', $key);

            // if there is another array found recrusively call this function
            if (is_array($value))
            {
                // create a new node unless this is an array of elements
                $node = ArrayToXML::isAssoc($value) ? $xml->addChild($key) : $xml;

                // recrusive call - pass $key as the new rootNodeName
                ArrayToXML::toXml($value, $key, $node);
            }
            else
            {
                // add single node.
                $value = htmlentities($value);
                $xml->addChild($key,$value);
            }

        }
        // pass back as string. or simple xml object if you want!
        return $xml->asXML();
    }

    // determine if a variable is an associative array
    public static function isAssoc( $array ) {
        return (is_array($array) &amp;&amp; 0 !== count(array_diff_key($array, array_keys(array_keys($array)))));
    }
}
</code></pre> ]]></description>
<pubDate>Wed, 26 Aug 2009 09:35:41 GMT</pubDate>
<guid>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</guid>
</item>
<item>
<title>Jpsy said on 6/4/09</title>
<link>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</link>
<description><![CDATA[ Sorry for the mess that Markdown produced from my code. I tried, but it does not get any better. Let's try again with manual formatting...

<p>Nice piece of code that shortened my way. 
But visual77 and hradek are both correct with their fixes (var by reference, is_null, wrongly removing non alphas). 
To sum it up, here is my changed code:</p>

<pre><code>class ArrayToXML
{
	/**
	 * The main function for converting to an XML document.
	 * Pass in a multi dimensional array and this recrusively loops through and builds up an XML document.
	 *
	 * @param array $data
	 * @param string $rootNodeName - what you want the root node to be - defaultsto data.
	 * @param SimpleXMLElement $xml - should only be used recursively
	 * @return string XML
	 */
	public static function toXml($data, $rootNodeName = 'data', &amp;$xml=null)
	{
		// turn off compatibility mode as simple xml throws a wobbly if you don't.
		if (ini_get('zend.ze1_compatibility_mode') == 1)
		{
			ini_set ('zend.ze1_compatibility_mode', 0);
		}
		
		if (is_null($xml))
		{
			$xml = simplexml_load_string("");
		}
		
		// loop through the data passed in.
		foreach($data as $key => $value)
		{
			// no numeric keys in our xml please!
			if (is_numeric($key))
			{
				// make string key...
				$key = "unknownNode_". (string) $key;
			}
			
			// delete any char not allowed in XML element names
			$key = preg_replace('/[^a-z0-9\-\_\.\:]/i', '', $key);
			
			// if there is another array found recrusively call this function
			if (is_array($value))
			{
				$node = $xml->addChild($key);
				// recrusive call.
				ArrayToXML::toXml($value, $rootNodeName, $node);
			}
			else 
			{
				// add single node.
                                $value = htmlentities($value);
				$xml->addChild($key,$value);
			}
			
		}
		// pass back as string. or simple xml object if you want!
		return $xml->asXML();
	}
}
</code></pre> ]]></description>
<pubDate>Thu, 04 Jun 2009 03:11:06 GMT</pubDate>
<guid>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</guid>
</item>
<item>
<title>Jpsy said on 6/4/09</title>
<link>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</link>
<description><![CDATA[ <p>Nice piece of code that shortened my way.
But visual77 and hradek are both correct with their fixes (var by reference, is_null, wrongly removing non alphas). 
To sum it up, here is my changed code:</p>

<p>`
class ArrayToXML
{
    /**
     * The main function for converting to an XML document.
     * Pass in a multi dimensional array and this recrusively loops through and builds up an XML document.
     *
     * @param array $data
     * @param string $rootNodeName - what you want the root node to be - defaultsto data.
     * @param SimpleXMLElement $xml - should only be used recursively
     * @return string XML
     */
    public static function toXml($data, $rootNodeName = 'data', &amp;$xml=null)
    {
        // turn off compatibility mode as simple xml throws a wobbly if you don't.
        if (ini<em>get('zend.ze1</em>compatibility<em>mode') == 1)
        {
            ini</em>set ('zend.ze1<em>compatibility</em>mode', 0);
        }</p>

<pre><code>    if (is_null($xml))
    {
        $xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><$rootNodeName />");
    }

    // loop through the data passed in.
    foreach($data as $key => $value)
    {
        // no numeric keys in our xml please!
        if (is_numeric($key))
        {
            // make string key...
            $key = "unknownNode_". (string) $key;
        }

        // delete any char not allowed in XML element names
        $key = preg_replace('/[^a-z0-9\-\_\.\:]/i', '', $key);

        // if there is another array found recrusively call this function
        if (is_array($value))
        {
            $node = $xml->addChild($key);
            // recrusive call.
            ArrayToXML::toXml($value, $rootNodeName, $node);
        }
        else 
        {
            // add single node.
                            $value = htmlentities($value);
            $xml->addChild($key,$value);
        }

    }
    // pass back as string. or simple xml object if you want!
    return $xml->asXML();
}
</code></pre>

<p>}
`</p> ]]></description>
<pubDate>Thu, 04 Jun 2009 02:49:10 GMT</pubDate>
<guid>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</guid>
</item>
<item>
<title>hradek said on 10/1/08</title>
<link>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</link>
<description><![CDATA[ Hi there, this is an excellent snippet and does the job fantastically when you want to accomplish the simple task of converting an array to XML.

Firstly, make sure you pass the $xml as a reference otherwise the stuff inside the recursive. Here is what I mean:

<pre><code>private function convertArray2xml($dataArray, $rootNodeName = 'dataSet', &amp;$xml = null)</code></pre>

Secondly, you can't check if a variable is null the way you do. Here is how it should look:

<pre><code>if(isnull($xml))
{
        $xml = simplexml_load_string("");
}</code></pre>

Finally, to implement this in your code can be very straight forward. After you connect to your database and get back your result set as an array run it through this function. I took it out of this wrapper class and stuck it into my MySQL DBI. ]]></description>
<pubDate>Wed, 01 Oct 2008 19:41:05 GMT</pubDate>
<guid>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</guid>
</item>
<item>
<title>visual77 said on 9/24/08</title>
<link>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</link>
<description><![CDATA[ In response to my previous comment - ignore item #4. Rereading the code shows me that I missed the section that replaces numeric keys with a string value. However, it will behave oddly. This code replaces "4" with "unknownNode_4" right before removing all non alpha characters, which converts it to "unknownNode". ]]></description>
<pubDate>Wed, 24 Sep 2008 00:39:04 GMT</pubDate>
<guid>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</guid>
</item>
<item>
<title>visual77 said on 9/24/08</title>
<link>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</link>
<description><![CDATA[ This is not a bad little snippet of code, but it has a few drawbacks.

First, it uses Simple XML, which is easier to use than DOMDocument, but is lacking DOMXpath and requires a bit of conversion before you can use it with the XSLTProcessor.

Second, it only lets you fire it off once before returning an XML tree. Further modification is difficult, and would require running it multiple times and then combining the results.

Third, it only supports arrays. Trying to pass a string, can only work if it is an element of the array. If you passed an array of DOMElements, or a mixed collection, or anything besides multidimensional arrays containing only arrays, strings, nulls, or ints, it'll crash.

Fourth, if the array keys are all numeric, it will attempt to add an invalid node to the tree and crash ungracefully.

Fifth, it has no built in support for an XSL driven website and can only be used loosely in conjuction with PHP's XSLTProcessor to that effect.

For an object that fixes all of these issues, check out the DOMi project at http://domi.sourceforge.net - this object is an improved version of DOMDocument, combined with DOMXpath and XSLTProcessor that is built to allow most PHP data structures to be converted to an XML tree flawlessly, lets you run that function multiple times to build up elaborate XML trees, and is designed with XSLTProcessor in mind, and lets you convert from an array to an XML tree and render through the XSLTProcessor in as few as three lines. ]]></description>
<pubDate>Wed, 24 Sep 2008 00:31:23 GMT</pubDate>
<guid>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</guid>
</item>
<item>
<title>maverickblair said on 1/22/08</title>
<link>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</link>
<description><![CDATA[ <p>how do you implement this?
where are you connecting to the database table?</p>
 ]]></description>
<pubDate>Tue, 22 Jan 2008 12:01:54 GMT</pubDate>
<guid>http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/</guid>
</item>
</channel>
</rss>
