I had the same issue and problems finding a simple solution. The solution below makes use of DOMDocument to allow for Pretty Printing. If you don't want Pretty Printing set $doc->formatOutput = FALSE;
I humbly submit the following PHP function:
function array2xml($data, $name='root', &$doc=null, &$node=null){
if ($doc==null){
$doc = new DOMDocument('1.0','UTF-8');
$doc->formatOutput = TRUE;
$node = $doc;
}
if (is_array($data)){
foreach($data as $var=>$val){
if (is_numeric($var)){
array2xml($val, $name, $doc, $node);
}else{
if (!isset($child)){
$child = $doc->createElement($name);
$node->appendChild($child);
}
array2xml($val, $var, $doc, $child);
}
}
}else{
$child = $doc->createElement($name);
$node->appendChild($child);
$textNode = $doc->createTextNode($data);
$child->appendChild($textNode);
}
if ($doc==$node) return $doc->saveXML();
}//array2xml
Using the following test data and call:
$array = [
'name' => 'ABC',
'email' => 'email@email.com',
'phones' =>
[
'phone' =>
[
[
'mobile' => '9000199193',
'land' => '9999999',
],
[
'mobile' => '9000199193',
'land' => '9999999',
],
[
'mobile' => '9000199194',
'land' => '5555555',
],
[
'mobile' => '9000199195',
'land' => '8888888',
],
],
],
];
//Specify the $array and a name for the root container
echo array2xml($array, 'contact');
You get the following results:
<?xml version="1.0" encoding="UTF-8"?>
<contact>
<name>ABC</name>
<email>email@email.com</email>
<phones>
<phone>
<mobile>9000199193</mobile>
<land>9999999</land>
</phone>
<phone>
<mobile>9000199193</mobile>
<land>9999999</land>
</phone>
<phone>
<mobile>9000199194</mobile>
<land>5555555</land>
</phone>
<phone>
<mobile>9000199195</mobile>
<land>8888888</land>
</phone>
</phones>
</contact>
I hope this helps.