Skip to content

Instantly share code, notes, and snippets.

@Onheiron
Created June 30, 2012 22:29
Show Gist options
  • Save Onheiron/3025822 to your computer and use it in GitHub Desktop.
Save Onheiron/3025822 to your computer and use it in GitHub Desktop.
PHP - ArrayToXML Converter
<?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;
}
?>
@Onheiron
Copy link
Author

Improved Array To XML conversion function for PHP using SimpleXML and recursion.

First call can be both:

$xml = arrayToXML($array,"root"); 
// where "root" is the name of the root element in the XML you want to create

or

$xml = arrayToXML($array,"subroot",$superXml); 
// where $superXml is an XML DOM element where you want to add your XML as a child.

@Onheiron
Copy link
Author

Onheiron commented Jul 3, 2012

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