Created
August 29, 2012 08:39
-
-
Save lotas/3508642 to your computer and use it in GitHub Desktop.
array_to_xml.php
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 | |
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