Skip to content

Instantly share code, notes, and snippets.

@Tiriel
Created October 19, 2016 09:19
Show Gist options
  • Save Tiriel/6082a2d1b9bc5d04b68a2947d4827831 to your computer and use it in GitHub Desktop.
Save Tiriel/6082a2d1b9bc5d04b68a2947d4827831 to your computer and use it in GitHub Desktop.
Function found on StackOverflow
<?php
// function defination to convert array to xml
function array_to_xml( $data, &$xml_data ) {
foreach( $data as $key => $value ) {
if( is_numeric($key) ){
$key = 'item'.$key; //dealing with <0/>..<n/> issues
}
if( is_array($value) ) {
$subnode = $xml_data->addChild($key);
array_to_xml($value, $subnode);
} else {
$xml_data->addChild("$key",htmlspecialchars("$value"));
}
}
}
// initializing or creating array
$data = array('total_stud' => 500);
// creating object of SimpleXMLElement
$xml_data = new SimpleXMLElement('<?xml version="1.0"?><data></data>');
// function call to convert array to xml
array_to_xml($data,$xml_data);
//saving generated xml file;
$result = $xml_data->asXML('/file/path/name.xml');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment