Last active
December 10, 2015 00:39
-
-
Save seebz/4352810 to your computer and use it in GitHub Desktop.
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 array2xml($arr, $root = false, $header = false) { | |
| if (! function_exists('is_hash')) { | |
| function is_hash($var) { | |
| return ( is_array($var) && array_keys($var) !== range(0, count($var)-1) ); | |
| } | |
| } | |
| if (! function_exists('normalize_array2xml')) { | |
| function normalize_array2xml($arr, $level = 0) { | |
| if (is_object($arr)) $arr = get_object_vars($arr); | |
| for ($i = 0, $tabs = ''; $i < $level; $i++) $tabs .= "\t"; | |
| $output = array(); | |
| foreach($arr as $k => $v) { | |
| if (is_null($v)) { | |
| continue; | |
| } | |
| elseif (is_bool($v)) { | |
| $value = ($v === true ? 'TRUE' : 'FALSE'); | |
| $output[] = $tabs . sprintf('<%1$s>%2$s</%1$s>', $k, $value); | |
| } | |
| elseif ($v === '') { | |
| $output[] = $tabs . sprintf('<%1$s/>', $k); | |
| } | |
| elseif (is_scalar($v)) { | |
| $value = $v; | |
| $output[] = $tabs . sprintf('<%1$s>%2$s</%1$s>', $k, htmlspecialchars($value)); | |
| } | |
| elseif (is_hash($v)) { | |
| $value = normalize_array2xml($v, $level + 1); | |
| $output[] = $tabs . sprintf('<%1$s>%2$s</%1$s>', $k, "\n{$value}\n{$tabs}"); | |
| } | |
| elseif (is_array($v)) { | |
| foreach($v as $w) { | |
| $output[] = normalize_array2xml(array($k => $w), $level); | |
| } | |
| } | |
| } | |
| return implode("\n", $output); | |
| } | |
| } | |
| if ($root) { | |
| $arr = array((string) $root => $arr); | |
| } | |
| $xml = normalize_array2xml($arr); | |
| if ($header) { | |
| $xml = '<?xml version="1.0"?>' . "\n" . $xml; | |
| } | |
| return $xml; | |
| } | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment