Skip to content

Instantly share code, notes, and snippets.

@gowon
Last active August 29, 2015 13:57
Show Gist options
  • Save gowon/9541628 to your computer and use it in GitHub Desktop.
Save gowon/9541628 to your computer and use it in GitHub Desktop.
Simple XML Encoder
<?php
function simple_xml_encoder($data, $rootNode = 'response', $node = 'string') {
function traverse($data, $node) {
$xml = '';
if (is_array($data) || is_object($data)) {
foreach ($data as $key => $value) {
if (is_numeric($key)) {
$key = $node;
}
if (empty($value)) {
$format = '<%1$s />';
}
else {
$format = '<%1$s>%2$s</%1$s>';
}
$xml .= sprintf($format, $key, traverse($value, $node));
}
} else {
$xml = htmlspecialchars($data, ENT_QUOTES);
}
return $xml;
}
$nodes = traverse($data, $node);
$format = '<%1$s>%2$s</%1$s>';
$xml = sprintf($format, $rootNode, $nodes);
return $xml;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment