15.7.09

Converting PHP Array to XML

While implementing our new project PreviewMyEmail we needed an array to XML converter. Here is a very simple solution for all whom need such a stuff. If you need a structure as
<object><property1/><property2/></object>
you need to send array as an arrays of object_1, object_2 and so on then should give suffix as '_'. That's it! By the way, $xml is a SimpleXML object.


function _toXML($xml, $array, $suffix = '')
{
foreach($array as $key => $value)
{
if(is_array($value))
{
if($suffix != '')
{
$key = explode($suffix, $key);
$key = $key[0];
}
$node = $xml->addChild(strtolower($key));
$this->_toXML($node, $value);
}
else
{
$safe_value = preg_replace('/&(?!\w+;)/', '&', $value);
$xml->addChild($key, $safe_value);
}
}
return $xml;
}