How to Convert a PHP array to xml

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

Code Snippet: Array to XML in PHP

This article answers how to convert array to XML in PHP. Here’s a snippet from the article.

<?php
$students_data = [
    "Andy" => ["ID"=>"1001", "Electives"=>["Computer Science", "Calculus"]],
    "Benjamin" => ["ID"=>"1002", "Elective"=>["Electronics", "Digital Logic Design"]],
    "Catheline" => ["ID"=>"1003", "Elective"=>["Economics", "Political Science"]],
    "Dexter" => ["ID"=>"1004", "Elective"=>["Computer Science", "Discrete Mathematics"]],
    "Eion" => ["ID"=>"1004", "Elective"=>["Computer Science", "Digital Logic Design"]],
    "Franklin" => ["ID"=>"1005", "Elective"=>["Mathematics", "Physics"]],
];
 
function arraytoXML($arr, &$xml)
{
    foreach($arr as $key => $value)
    {
        if(is_int($key))
        {
            $key = 'Element'.$key;  //To avoid numeric tags like <0></0>
        }
        if(is_array($value))
        {
            $label = $xml->addChild($key);
            arrayToXml($value, $label);  //Adds nested elements.
        }
        else
        {
            $xml->addChild($key, $value);
        }
    }
}
 
$xml = new SimpleXMLElement('&lt;?xml version="1.0" encoding="UTF-8"?>&lt;Students>&lt;/Students>');
 
arraytoXML($students_data, $xml);
$xml->asXML('output.xml');
?>

That’s one way of doing the conversion. The article features a third-party package that will make your life a lot easier than reinventing the wheel. Stay till the end to learn more.

Relevant Content: JSON & XML Conversion 

In the article “How to convert JSON to XML in PHP,” we learned some fundamentals of JSON and XML and the SimpleXMLElement class. We also defined a custom function arraytoXML. So, we highly recommend reading that article for a nice headstart. 

This article reuses the custom function defined there. So, let’s see how to convert array to XML in PHP.

Scenario: Students’ Data in a PHP Array to XML

Background & Setup: PHP Array

Suppose you are programming an API that serves XML response. The data source returns an array, and you need to convert that to XML. That’s the challenge here, and this article is all about solving this challenge.

Let’s get setup.

Here’s an example of an array containing data about students and their elective subjects. This example is fairly good as we have a multidimensional array structure. The objective here is to convert this multidimensional array to XML in PHP.

$students_data = [
    "Andy" => ["ID"=>"1001", "Electives"=>["Computer Science", "Calculus"]],
    "Benjamin" => ["ID"=>"1002", "Elective"=>["Electronics", "Digital Logic Design"]],
    "Catheline" => ["ID"=>"1003", "Elective"=>["Economics", "Political Science"]],
    "Dexter" => ["ID"=>"1004", "Elective"=>["Computer Science", "Discrete Mathematics"]],
    "Eion" => ["ID"=>"1004", "Elective"=>["Computer Science", "Digital Logic Design"]],
    "Franklin" => ["ID"=>"1005", "Elective"=>["Mathematics", "Physics"]],
];
 

Option 1: Convert Array to XML in PHP using Custom Function

Remember that the article mentions the arraytoXML function defined in JSON to XML article. This function recursively builds the XML document calling methods of SimpleXMLElement class. Here’s the function.

function arraytoXML($arr, &$xml)
{
    foreach($arr as $key => $value)
    {
        if(is_int($key))
        {
            $key = 'Element'.$key;  //To avoid numeric tags like <0></0>
        }
        if(is_array($value))
        {
            $label = $xml->addChild($key);
            arrayToXml($value, $label);  //Adds nested elements.
        }
        else
        {
            $xml->addChild($key, $value);
        }
    }
}

The function adds keys and values to form an XML tag. It recursively calls itself when it encounters a nested array. This logic is super helpful in parsing multidimensional arrays. Also, it caters to the integer keys of an array by prefixing it with ‘Element’

Note that the function expects an array and SimpleXMLElement object. The SimpleXMLElement object defines the root node of the XML, and the function eventually adds the child nodes to it. So, let’s initialize an object.

$xml = new SimpleXMLElement('&lt;?xml version="1.0" encoding="UTF-8"?>&lt;Students>&lt;/Students>');

See! Initializing is super easy. The argument to the constructor defines the XML version tag and the root tag, which in this case is <Students></Students>.

Now, we need to pass the array and SimpleXMLElement object to the function.

arraytoXML($students_data, $xml);

After the function executes, the SimpleXMLElement object will be populated with the array data. Finally, we need to save the output to a destination. So, let’s save it to a file for now.

$xml->asXML('output.xml');

The SimpleXMLElement provides a function asXML that makes file writing super convenient. Let’s put this all together.

<?php
$students_data = [
    "Andy" => ["ID"=>"1001", "Electives"=>["Computer Science", "Calculus"]],
    "Benjamin" => ["ID"=>"1002", "Elective"=>["Electronics", "Digital Logic Design"]],
    "Catheline" => ["ID"=>"1003", "Elective"=>["Economics", "Political Science"]],
    "Dexter" => ["ID"=>"1004", "Elective"=>["Computer Science", "Discrete Mathematics"]],
    "Eion" => ["ID"=>"1004", "Elective"=>["Computer Science", "Digital Logic Design"]],
    "Franklin" => ["ID"=>"1005", "Elective"=>["Mathematics", "Physics"]],
];
 
function arraytoXML($arr, &$xml)
{
    foreach($arr as $key => $value)
    {
        if(is_int($key))
        {
            $key = 'Element'.$key;  //To avoid numeric tags like <0></0>
        }
        if(is_array($value))
        {
            $label = $xml->addChild($key);
            arrayToXml($value, $label);  //Adds nested elements.
        }
        else
        {
            $xml->addChild($key, $value);
        }
    }
}
 
$xml = new SimpleXMLElement('&lt;?xml version="1.0" encoding="UTF-8"?>&lt;Students>&lt;/Students>');
 
arraytoXML($students_data, $xml);
$xml->asXML('output.xml');
?>

Here’s what the output looks like.

&lt;?xml version="1.0" encoding="UTF-8"?>
&lt;students>
	&lt;Andy>
		&lt;ID>1001&lt;/ID>
		&lt;Electives>
			&lt;Element0>Computer Science&lt;/Element0>
			&lt;Element1>Calculus&lt;/Element1>
		&lt;/Electives>
	&lt;/Andy>
	&lt;Benjamin>
		&lt;ID>1002&lt;/ID>
		&lt;Elective>
			&lt;Element0>Electronics&lt;/Element0>
			&lt;Element1>Digital Logic Design&lt;/Element1>
		&lt;/Elective>
	&lt;/Benjamin>
	&lt;Catheline>
		&lt;ID>1003&lt;/ID>
		&lt;Elective>
			&lt;Element0>Economics&lt;/Element0>
			&lt;Element1>Political Science&lt;/Element1>
		&lt;/Elective>
	&lt;/Catheline>
	&lt;Dexter>
		&lt;ID>1004&lt;/ID>
		&lt;Elective>
			&lt;Element0>Computer Science&lt;/Element0>
			&lt;Element1>Discrete Mathematics&lt;/Element1>
		&lt;/Elective>
	&lt;/Dexter>
	&lt;Eion>
		&lt;ID>1004&lt;/ID>
		&lt;Elective>
			&lt;Element0>Computer Science&lt;/Element0>
			&lt;Element1>Digital Logic Design&lt;/Element1>
		&lt;/Elective>
	&lt;/Eion>
	&lt;Franklin>
		&lt;ID>1005&lt;/ID>
		&lt;Elective>
			&lt;Element0>Mathematics&lt;/Element0>
			&lt;Element1>Physics&lt;/Element1>
		&lt;/Elective>
	&lt;/Franklin>
&lt;/students>

Option 2: Convert Array to XML in PHP using a Third Party Package

We’ll be using spatie/array-to-xml for array to XML PHP. First, we need to install it through Composer.

composer require spatie/array-to-xml

The package exports a class ArraytoXML, which has a static method convert. Here’s how to convert a PHP multidimensional array to XML.

<?php
require __DIR__ . '/vendor/autoload.php';
 
$students_data = [
    "Andy" => ["ID"=>"1001", "Electives"=>["Computer Science", "Calculus"]],
    "Benjamin" => ["ID"=>"1002", "Elective"=>["Electronics", "Digital Logic Design"]],
    "Catheline" => ["ID"=>"1003", "Elective"=>["Economics", "Political Science"]],
    "Dexter" => ["ID"=>"1004", "Elective"=>["Computer Science", "Discrete Mathematics"]],
    "Eion" => ["ID"=>"1004", "Elective"=>["Computer Science", "Digital Logic Design"]],
    "Franklin" => ["ID"=>"1005", "Elective"=>["Mathematics", "Physics"]],
];
   
 
$xml = Spatie\ArrayToXml\ArrayToXml::convert($students_data, 'Students'); //Returns XML
?>

Perfect! It makes our lives a lot easier. Observe that the function expects a second optional argument that specifies the root element name. Read more about this function on the official site.

Note: XML Attributes and Arrays

The spatie/ArrayToXml defines a specific syntax for parsing XML attributes. The catch here is that the method assumes "_attributes" key in the array specialized for XML attributes. The following example clarifies it.

<?php
require __DIR__ . '/vendor/autoload.php';
 
$shapes = [
    "Circle" => [
        "_attributes" => ["shape" => "round"],
        "color" => "red"
    ],
    "Square" => [
        "_attributes" => ["shape" => "box"],
        "color" => "purple"
    ]  
];
   
 
$xml = Spatie\ArrayToXml\ArrayToXml::convert($shapes, 'Shapes'); //Returns XML
 
?>

The method will place the shape as an attribute to the tags Circle and Square. Here’s the output.

&lt;?xml version="1.0"?>
&lt;Shapes>
 &lt;Circle shape="round">
  &lt;color>red&lt;/color>
 &lt;/Circle>
 &lt;Square shape="box">
  &lt;color>purple&lt;/color>
 &lt;/Square>
&lt;/Shapes>

Check the attributes and their values! You can pass as many attributes to the “_attributes” array and the method will pick them up.

Conclusion

Wrap Up

We have seen PHP array to XML through a couple of options. The first option uses a custom function that recursively builds up the XML tree. The second option uses a third-party package to convert the array to XML in PHP. The third-party package also features an option for XML attributes.

Functions and Packages Mentioned

SimpleXMLElement Class: (PHP 5, 7, 8) This a built-in PHP class readily available for XML related operations. The class object represents an XML document and defines relevant methods to build up an XML document. Many of its methods have been used throughout this article.

is_array: (PHP 4, 5, 7, 8) This is a core PHP function that has been available since PHP 4. This is quite a handy function that verifies if a variable is actually an array. You will need this function in conditional statements and recursive calls more often.

spatie/array-to-xml: (PHP 8) This package is available in the Composer package repository. It converts an array to XML in PHP. At the time of writing this article, it has 5,175,229 downloads and around 912 stars signifying that it is a useful package. I must commend the documentation as it is super convenient for starters. 

Hope you’ve liked this article. Stay tuned for more at FuelingPHP.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.