Skip to content

Instantly share code, notes, and snippets.

@s2ar
Last active April 23, 2016 08:21
Show Gist options
  • Save s2ar/b5973be6f7a77b0005cc to your computer and use it in GitHub Desktop.
Save s2ar/b5973be6f7a77b0005cc to your computer and use it in GitHub Desktop.
array to xml
<?php
//function defination to convert array to xml
function array_to_xml($array, &$xml_user_info) {
foreach($array as $key => $value) {
if(is_array($value)) {
if(!is_numeric($key)){
$subnode = $xml_user_info->addChild("$key");
array_to_xml($value, $subnode);
}else{
$subnode = $xml_user_info->addChild("item$key");
array_to_xml($value, $subnode);
}
}else {
$xml_user_info->addChild("$key",htmlspecialchars("$value"));
}
}
}
//creating object of SimpleXMLElement
$xml_user_info = new SimpleXMLElement("<?xml version=\"1.0\"?><products></products>");
//function call to convert array to xml
array_to_xml($users_array,$xml_user_info);
//saving generated xml file
$xml_file = $xml_user_info->asXML('users.xml');
//success and error message based on xml creation
if($xml_file){
echo 'XML file have been generated successfully.';
}else{
echo 'XML file generation error.';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment