Return to Snippet

Revision: 62686
at March 6, 2013 07:03 by abrahamsustaita


Initial Code
<?php
$toXml = function ( &$xml, $data ) use ( &$toXml ) {
	foreach ( $data as $key => $value ) {
		$xml->addChild ( $key );
		if ( is_array ( $value ) ) {
			$toXml ( $xml->$key, $value );
		} else {
			$xml->$key = $value;
		}
	}
};

$data = array (
    "key1" => "value2",
    "key2" => array (
        "subkey1" => "subvalue1"
    )
);
$xml = new SimpleXMLElement ( "<root />" );
$toXml ( $xml, $data );

echo $xml->asXML();

Initial URL


Initial Description
This snippet is a lambda function (anonymous function) to create an xml from an array. It uses recursiveness.

Initial Title
Lambda function to create XML from Array

Initial Tags
php, array, xml

Initial Language
PHP