note 101949 modified in book.simplexml by danbrown
| From: | danbrown@php.net | Date: | Wed, 19 Jan 2011 20:55:10 +0000 |
| Subject: | note 101949 modified in book.simplexml by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-175910@lists.php.net to get a copy of this message | ||
Here's a function I came up with to convert an associative array to XML. Works for
multidimensional arrays as well.
<?php
function assocArrayToXML($root_element_name,$ar)
{
$xml = new SimpleXMLElement("<?xml
version=\"1.0\"?><{$root_element_name}></{$root_element_name}>");
$f = create_function('$f,$c,$a','
foreach($a as $k=>$v) {
if(is_array($v)) {
$ch=$c->addChild($k);
$f($f,$ch,$v);
} else {
$c->addChild($k,$v);
}
}');
$f($f,$xml,$ar);
return $xml->asXML();
}
?>
--was--
Here's a function I came up with to convert an associative array to XML. Works for
multidimensional arrays as well.
function assocArrayToXML($root_element_name,$ar)
{
$xml = new SimpleXMLElement("<?xml
version=\"1.0\"?><{$root_element_name}></{$root_element_name}>");
$f = create_function('$f,$c,$a','
foreach($a as $k=>$v) {
if(is_array($v)) {
$ch=$c->addChild($k);
$f($f,$ch,$v);
} else {
$c->addChild($k,$v);
}
}');
$f($f,$xml,$ar);
return $xml->asXML();
}
http://php.net/manual/en/book.simplexml.php