Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created August 27, 2018 14:47
Show Gist options
  • Save kobus1998/6390d83d906f70c2387aba23f0687dda to your computer and use it in GitHub Desktop.
Save kobus1998/6390d83d906f70c2387aba23f0687dda to your computer and use it in GitHub Desktop.
array to xml
<?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