Serialize array / object as XML in PHP « home
posted on 12:31 - 06 December 2010 | posted by Lev
last modified on 12:32 - 06 December 2010 | last modified by Lev
As far as I know, there doesn't seem to be a built in way to do this with PHP's simplexml class, so I wrote a simple function you're free to use:
PHP CODE
function SerializeAsXML ($obj, $depth = 0)
{
if (is_array($obj) || is_object($obj))
{
for ($i = 0; $i <= $depth; $i++)
{
$tabs .= "\t";
}
foreach ($obj as $o_i => $o_v)
{
$useTab = false;
$d .= $tabs . "<{$o_i}>";
if (is_array($o_v) || is_object($o_v))
{
$tabs++;
$d .= "\n" . SerializeAsXML($o_v, ($depth + 1));
$useTab = true;
}
else
{
$d .= $o_v;
}
if ($useTab)
{
$d .= $tabs;
}
$d .= "</{$o_i}>\n";
}
}
return $d;
}
{
if (is_array($obj) || is_object($obj))
{
for ($i = 0; $i <= $depth; $i++)
{
$tabs .= "\t";
}
foreach ($obj as $o_i => $o_v)
{
$useTab = false;
$d .= $tabs . "<{$o_i}>";
if (is_array($o_v) || is_object($o_v))
{
$tabs++;
$d .= "\n" . SerializeAsXML($o_v, ($depth + 1));
$useTab = true;
}
else
{
$d .= $o_v;
}
if ($useTab)
{
$d .= $tabs;
}
$d .= "</{$o_i}>\n";
}
}
return $d;
}
This accepts either an array or an object and takes care of the tabbing/formatting (at least in the manner I like; you may tweak it to your liking).
Related Items »
- about » How can I get Theia, and does it cost anything?
- home » Mental note: ensure magic quotes are no longer used
- download » Theia 1.0.0b1
- home » Listing Theia in resource index sites
- php » PHP 5.3 compatibility
- download » Theia 1.0.0b2
- services » web design
- home » Receive a free installation of Theia until the end of July!
- home » International telephone country codes (in XML format using ISO 639-1)
- requests » stored event data (serialize/unserialize)






