Skip to content

Instantly share code, notes, and snippets.

@phaberest
Last active September 20, 2016 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phaberest/763a14a9b15fbb6711addd40a15d668b to your computer and use it in GitHub Desktop.
Save phaberest/763a14a9b15fbb6711addd40a15d668b to your computer and use it in GitHub Desktop.
[PHP] Array to XML
private function arrayToXML($data, &$xml)
{
foreach ($data as $key => $value) {
if (is_array($value)) {
if (is_numeric($key)) {
$key = 'item'.$key; //dealing with <0/>..<n/> issues
}
$subnode = $xml->addChild($key);
array_to_xml($value, $subnode);
} else {
$xml->addChild("$key", htmlspecialchars("$value"));
}
}
}
private function prepareXML(array $array)
{
$xml = new SimpleXMLElement('<?xml version="1.0"?><data></data>');
$this->array_to_xml($data, $xml);
return $xml; # Get XML with $->asXML(), save it with $->asXML({path})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment