Last active
August 29, 2015 13:57
-
-
Save gowon/9541628 to your computer and use it in GitHub Desktop.
Simple XML Encoder
This file contains 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 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