Convert array to XML in PHP

Many times we need store the data as a XML into the database or into the file for later use. For fulfil this need, we will need to convert the data to XML and save the XML file. In this tutorial we will discuss, how to create XML from array in PHP. We have created a simple script for convert PHP array to XML. You can easily generate XML file from PHP array and save the XML file. You can convert all types of array like Associative array or Multidimensional arrays.

PHP Array:

At first we will store the users data into a variable ($users_array).

$users_array = array(
"total_users" => 3,
"users" => array(
"id" => 1,
"name" => "Nitya",
"address" => array(
"country" => "India",
"city" => "Kolkata",
"zip" => 700102,
"id" => 2,
"name" => "John",
"address" => array(
"country" => "USA",
"city" => "Newyork",
"zip" => "NY1234",
"id" => 3,
"name" => "Viktor",
"address" => array(
"country" => "Australia",
"city" => "Sydney",
"zip" => 123456,

Array to XML:

Now we will convert the users array to XML using PHP SimpleXML. Please follow the comment tags for better understand.

//function defination to convert array to xml
function array_to_xml($array, &$xml_user_info) {
$array as $key => $value) {
is_array($value)) {
$subnode $xml_user_info->addChild("$key");
$subnode $xml_user_info->addChild("item$key");
        }else {

//creating object of SimpleXMLElement
$xml_user_info = new SimpleXMLElement("<?xml version=\"1.0\"?><user_info></user_info>");

//function call to convert array to xml

//saving generated xml file
$xml_file $xml_user_info->asXML('users.xml');
//success and error message based on xml creation
'XML file have been generated successfully.';
'XML file generation error.';

XML File:

The users.xml file contains the following xml.

<?xml version="1.0"?>

Insert XML Into Databse

If you want to save the XML into the database, then replace the $xml_file variable line with the following code line. Now you can insert $xml_file variable into the database.

$xml_file $xml_user_info->asXML();

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

Recommended Tutorials For You


  1. Baba Said...
    • CodexWorld Said...
  2. Samantha Machado Said...

Leave a reply