Created
August 27, 2018 14:47
-
-
Save kobus1998/6390d83d906f70c2387aba23f0687dda to your computer and use it in GitHub Desktop.
array to xml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function isAssoc(array $arr) | |
{ | |
if (array() === $arr) return false; | |
return array_keys($arr) !== range(0, count($arr) - 1); | |
} | |
function toXml($name, $a) { | |
$sReturn = "<$name>"; | |
foreach($a as $key => $val) { | |
if (is_array($val)) { | |
if (isAssoc($val)) { | |
$sReturn .= toXml($key, $val); | |
} else { | |
foreach($val as $sub) { | |
$sReturn .= "<$key>$sub</$key>"; | |
} | |
} | |
} else { | |
$sReturn .= "<$key>$val</$key>"; | |
} | |
} | |
$sReturn .= "</$name>"; | |
return $sReturn; | |
} | |
echo toXml("root", [ | |
"me" => 1, | |
"items" => [1,2,3,4,5,6] | |
]); | |
/* | |
<root> | |
<me>1</me> | |
<items>1</items> | |
<items>2</items> | |
<items>3</items> | |
<items>4</items> | |
<items>5</items> | |
<items>6</items> | |
</root> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment