Skip to content

Instantly share code, notes, and snippets.

@reimund
Last active December 16, 2015 18:49
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 reimund/5480320 to your computer and use it in GitHub Desktop.
Save reimund/5480320 to your computer and use it in GitHub Desktop.
Php port of my xml serializer.
<?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