Last active
December 16, 2015 18:49
-
-
Save reimund/5480320 to your computer and use it in GitHub Desktop.
Php port of my xml serializer.
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 dict2xml($d, $root_node=null, $use_attr=true) | |
{ | |
$wrap = (null == $root_node or is_plain_array($d)) ? false : true; | |
$root = (null == $root_node) ? 'objects' : $root_node; | |
$root_singular = ('s' == $root[strlen($root) - 1] and null == $root_node) | |
? substr($root, 0, strlen($root) - 1) | |
: $root; | |
$xml = ''; | |
$end_tag = ''; | |
$children = array(); | |
if (is_assoc($d)) { | |
if (!$use_attr) | |
$xml .= '>'; | |
foreach ($d as $key => $value) { | |
if (is_assoc($value)) | |
array_push($children, dict2xml($value, $key, $use_attr)); | |
else if (is_plain_array($value)) | |
array_push($children, dict2xml($value, $key, $use_attr)); | |
else if ($use_attr) | |
$xml .= ' ' . $key . '="' . $value . '"'; | |
else | |
$xml .= '<' . $key . '>' . $value . '</' . $key . '>'; | |
} | |
} else if (is_array($d)) | |
foreach ($d as $k => $value) | |
array_push($children, dict2xml($value, $root_singular, is_array($value) ? $use_attr : false)); | |
else | |
return '<' . $root . '>' . $d . '</' . $root . '>'; | |
if ($use_attr) | |
$end_tag = (0 < count($children)) ? '>' : '/>'; | |
else if (empty($children)) | |
$end_tag = '</' . $root . '>'; | |
if ($wrap or is_assoc($d)) | |
$xml = '<' . $root . $xml . $end_tag; | |
if (0 < count($children)) { | |
foreach ($children as $child) | |
$xml .= $child; | |
if ($wrap or is_assoc($d)) | |
$xml .= '</' . $root . '>'; | |
} | |
return $xml; | |
} | |
function is_assoc($arr) | |
{ | |
return is_array($arr) | |
? array_keys($arr) !== range(0, count($arr) - 1) | |
: false; | |
} | |
function is_plain_array($arr) | |
{ | |
return is_assoc($arr) ? false : is_array($arr); | |
} | |
// Example usage. | |
$mydict = array( | |
'name' => 'The Andersson\'s', | |
'size' => 4, | |
'children' => array( | |
'total-age' => 62, | |
'child' => array( | |
array('name' => 'Tom', 'sex' => 'male',), | |
array( | |
'name' => 'Betty', | |
'sex' => 'female', | |
'grandchildren' => array( | |
'grandchild' => array( | |
array('name' => 'herbert', 'sex' => 'male',), | |
array('name' => 'lisa', 'sex' => 'female',) | |
) | |
), | |
) | |
) | |
), | |
); | |
$xml = dict2xml($mydict, 'family'); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment