Created
June 30, 2012 22:29
-
-
Save Onheiron/3025822 to your computer and use it in GitHub Desktop.
PHP - ArrayToXML Converter
This file contains hidden or 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 | |
function arrayToXML($array,$parent,$xml=null){ | |
$index = 0; | |
if($xml == null){ | |
$xml = new SimpleXMLElement("<".$parent."/>"); | |
$child = $xml; | |
}else{ | |
$child = $xml->addChild($parent); | |
} | |
if(gettype($array) == 'array'){ | |
reset($array); | |
if(gettype(key($array)) == 'integer') unset($xml->$parent); | |
foreach($array as $key=>$element){ | |
if(gettype($key) == 'integer'){ | |
$xml = arrayToXML($element,$parent,$xml); | |
}else{ | |
$child = arrayToXML($element,$key,$child); | |
} | |
} | |
}else{ | |
$index = ($xml->$parent->count())-1; | |
$xml->$parent->$index = $array; | |
} | |
return $xml; | |
} | |
?> |
Update - Bug Fixing
The function now correctly generate "listed elements" i.e. list of xml elements with same tag name.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Improved Array To XML conversion function for PHP using SimpleXML and recursion.
First call can be both:
or