Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created February 27, 2018 11:00
Show Gist options
  • Save kobus1998/fc89dab7be6c48df1d425ee5b3e47c42 to your computer and use it in GitHub Desktop.
Save kobus1998/fc89dab7be6c48df1d425ee5b3e47c42 to your computer and use it in GitHub Desktop.
array to xml
<?php
$arr = [
'Rooms' => [
'1' => [
'name' => 'xxx',
'desc' => 'xxx'
],
'2' => [
'name' => 'yyy',
'desc' => 'yyy'
],
'3' => [
'name' => 'zzz',
'desc' => 'zzz'
]
]
];
function arrayToXml($arr, $response = '')
{
$x = "";
foreach ($arr as $key => $value)
{
if (is_array($value))
{
if (is_numeric($key))
{
$x .= "<Child Index=\"$key\">";
$x .= arrayToXml($value);
$x .= "</Child>";
}
else
{
$x .= "<$key>";
$x .= arrayToXml($value);
$x .= "</$key>";
}
}
else
{
$x .= "<$key>";
$x .= "$value";
$x .= "</$key>";
}
}
return $x;
}
echo arrayToXml($arr);
/*
<Rooms>
<Child Index="1">
<name>xxx</name>
<desc>xxx</desc>
</Child>
<Child Index="2">
<name>yyy</name>
<desc>yyy</desc>
</Child>
<Child Index="3">
<name>zzz</name>
<desc>zzz</desc>
</Child>
</Rooms>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment