I need to convert an array of indefinite depth to an xml string. I thought a recursive function would be better to this since the depth of the array is not unknown and is mostly of 3 levels. Here is the recursive function that I have come up so far
function array2xml($data, $key = ''){
if(!is_array($data)){
return "<".$key.">".$data."</".$key.">";
}
else{
foreach($data as $key => $value){
if(!is_array($value)){
return array2xml($value, $key);
}
else{
return "<".$key.">".array2xml($value)."</".$key.">";
}
}
}
This is the inital call but it returns only the first element in the array. For instance,
echo array2xml([
'students' => [
'names' => [
'frank' => '12',
'jason' => '13',
'beth' => '14'
],
'groups' => [
'yellow' => '165',
'green' => '98'
]
]
]);
Returns this output
<students><names><frank>12</frank></names></students>
Would appreciate it if someone could fix this recursive function so that the elements in the array are printed like this
<students>
<names>
<frankDiaz>12</frank>
<jasonVaaz>13</jason>
<bethDoe>14</beth>
</names>
<groups>
<yellow>165</yellow>
</groups>