Last active
June 28, 2018 23:15
-
-
Save loru88/367b69ae792b42bb6b20218c55267e13 to your computer and use it in GitHub Desktop.
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 | |
//function definition to convert array to xml | |
function array_to_xml($array, &$xml_user_info, $name = null) { | |
foreach($array as $key => $value) { | |
if(is_array($value)) { | |
if(!is_numeric($key)){ //just for associative array | |
array_to_xml($value, $xml_user_info, $key); | |
}else{ //just for indexed array | |
$subnode = $xml_user_info->addChild($name); | |
array_to_xml($value, $subnode); | |
} | |
}else { | |
$key = ($name ? $name : $key); //if it's from a pure indexed array, use the name of the key | |
$xml_user_info->addChild($key,htmlspecialchars($value)); | |
} | |
} | |
return $xml_user_info; | |
} | |
//EXAMPLE | |
$users_array = array( | |
"total_users" => 3, | |
"lista" => array( | |
"ciao", | |
"ciao2" | |
), | |
"users" => array( | |
array( | |
"id" => 1, | |
"name" => "Smith", | |
"address" => array( | |
"country" => "United Kingdom", | |
"city" => "London", | |
"zip" => 56789, | |
) | |
), | |
array( | |
"id" => 2, | |
"name" => "John", | |
"address" => array( | |
"country" => "USA", | |
"city" => "Newyork", | |
"zip" => "NY1234", | |
) | |
), | |
array( | |
"id" => 3, | |
"name" => "Viktor", | |
"address" => array( | |
"country" => "Australia", | |
"city" => "Sydney", | |
"zip" => 123456, | |
) | |
), | |
) | |
); | |
//creating object of SimpleXMLElement | |
$xml_user_info = new SimpleXMLElement("<?xml version=\"1.0\"?><user_info></user_info>"); | |
//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('test.xml'); |
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
<?xml version="1.0"?> | |
<user_info> | |
<total_users>3</total_users> | |
<lista>ciao</lista> | |
<lista>ciao2</lista> | |
<users> | |
<id>1</id> | |
<name>Smith</name> | |
<address>United Kingdom</address> | |
<address>London</address> | |
<address>56789</address> | |
</users> | |
<users> | |
<id>2</id> | |
<name>John</name> | |
<address>USA</address> | |
<address>Newyork</address> | |
<address>NY1234</address> | |
</users> | |
<users> | |
<id>3</id> | |
<name>Viktor</name> | |
<address>Australia</address> | |
<address>Sydney</address> | |
<address>123456</address> | |
</users> | |
</user_info> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment