Skip to content

Instantly share code, notes, and snippets.

@lotas
Created August 29, 2012 08:39
Show Gist options
  • Save lotas/3508642 to your computer and use it in GitHub Desktop.
Save lotas/3508642 to your computer and use it in GitHub Desktop.
array_to_xml.php
<?php
class Yangutu_Util_Xml
{
public static function arrayToXml(array $array, $attrTypeMap = array(), $returnAsString = true)
{
$xml = new SimpleXMLElement("<?xml version=\"1.0\"?><transaction></transaction>");
$xml = self::_makeXml($array, $xml, $attrTypeMap);
return $returnAsString ? $xml->asXML() : $xml;
}
private static function _makeXml(array $arr, SimpleXMLElement $xml, $attrTypeMap = array(), $path = '')
{
foreach ($arr as $k => $v)
{
$pathNew = $path.($path=='' ? '' : '.').$k;
if (is_array($v))
{
$elm = $xml->addChild($k);
self::_applyAttributes($elm, $pathNew, $attrTypeMap);
self::_makeXml($v, $elm, $attrTypeMap, $pathNew);
}
else
{
$elm = $xml->addChild($k, $v);
self::_applyAttributes($elm, $pathNew, $attrTypeMap);
}
}
return $xml;
}
private static function _applyAttributes(SimpleXMLElement $elm, $path, array $attrTypeMap)
{
if (isset($attrTypeMap[$path]))
{
foreach ($attrTypeMap[$path] as $attr => $value)
{
$elm->addAttribute($attr, $value);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment