I wanted to convert an array containing strings and other arrays of the same type into a simplexml object.
Here is the code of the function array2xml that I've developed to perform this conversion. Please note that this code is simple without any checks.
<?php
function array2xml($array, $tag) {
function ia2xml($array) {
$xml="";
foreach ($array as $key=>$value) {
if (is_array($value)) {
$xml.="<$key>".ia2xml($value)."</$key>";
} else {
$xml.="<$key>".$value."</$key>";
}
}
return $xml;
}
return simplexml_load_string("<$tag>".ia2xml($array)."</$tag>");
}
$test['type']='lunch';
$test['time']='12:30';
$test['menu']=array('entree'=>'salad', 'maincourse'=>'steak');
echo array2xml($test,"meal")->asXML();
?>