How to Convert JSON to XML in PHP

Summary:

You can convert a JSON object into an XML object in 2 steps. Use json_decode to transform it into a PHP array and then use SimpleXMLElement class to convert it into XML. Check out the article for more details.

JSON to XML in PHP

This article focuses on the conversion of JSON to XML in PHP. Here’s a sneak peek of the complete solution.

JSON to XML PHP Code Snippet

<?php
 
$JSON_arr = json_decode($JSON, true);
 
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><root></root>');
 
function arraytoXML($json_arr, &$xml)
{
    foreach($json_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);
        }
    }
}
 
arraytoXML($JSON_arr, $xml);
print_r($xml->asXML('output.xml'));
?>

Can’t understand what’s going on? Don’t worry, just stay tuned as this article will explain every bit in depth. 

Background: JSON, XML, SimpleXMLElement Class

JSON vs XML

JSON and XML have some similarities and differences in structure and function. Both are popular as data exchange formats in a client-server setup. That’s why applications that deal with both formats often need interconversion functionality between JSON and XML.

Follow the link to learn more about JSON vs XML. This article focuses on PHP JSON to XML conversion. 

PHP SimpleXMLElement Class

PHP SimpleXMLElement class bundles a set of methods for constructing XML elements programmatically in PHP. Methods like addChild and addAttribute are fundamental for building an XML markup. 

One cool thing about SimpleXMLElement is that it comes built into PHP. So, you don’t have to go through the hassle of installing third-party packages.

SimpleXMLElement class will support us in converting JSON to XML in PHP. The workflow starts with converting JSON to an array in PHP and then finally to XML using SimpleXMLElements methods. Here’s a flow diagram for the conversion process.

JSON to XML in PHP

Convert JSON to XML in PHP

The flow diagram above gives an overview of the process. Let’s dive into real work to realize this entire flow of JSON to XML PHP. Following is the mock JSON data.

$JSON = '[
{"id":1,"first_name":"Mendie","last_name":"Dunnett","email":"mdunnett0@usnews.com","gender":"Male","ip_address":"239.165.115.154"},
{"id":2,"first_name":"Florida","last_name":"Jurn","email":"fjurn1@ihg.com","gender":"Female","ip_address":"3.225.31.136"},
{"id":3,"first_name":"Ingeborg","last_name":"Robinson","email":"irobinson2@aol.com","gender":"Female","ip_address":"42.187.239.40"},
{"id":4,"first_name":"Ariana","last_name":"Ashborn","email":"aashborn3@usatoday.com","gender":"Non-binary","ip_address":"48.25.75.166"},
{"id":5,"first_name":"Melinda","last_name":"Mixture","email":"mmixture4@howstuffworks.com","gender":"Female","ip_address":"177.172.229.237"},
{"id":6,"first_name":"Eulalie","last_name":"Cheves","email":"echeves5@examiner.com","gender":"Female","ip_address":"132.241.220.47"},
{"id":7,"first_name":"Shermie","last_name":"Dedman","email":"sdedman6@google.com","gender":"Male","ip_address":"209.248.152.128"},
{"id":8,"first_name":"Marya","last_name":"Tromans","email":"mtromans7@1und1.de","gender":"Female","ip_address":"175.112.109.52"},
{"id":9,"first_name":"Concordia","last_name":"Cumberledge","email":"ccumberledge8@nhs.uk","gender":"Female","ip_address":"3.189.87.195"},
{"id":10,"first_name":"Doll","last_name":"Mutter","email":"dmutter9@tumblr.com","gender":"Female","ip_address":"248.64.142.26"}
]';

The next thing in the workflow is to convert it into a PHP array. To do this, we need to call json_decode in PHP.

$JSON_arr = json_decode($JSON, true);

Calling this function would return an associative array in PHP. Here’s a glimpse of the array returned due to the call above.

Array
(
    [0] => Array
        (
            [id] => 1
            [first_name] => Mendie
            [last_name] => Dunnett
            [email] => mdunnett0@usnews.com
            [gender] => Male
            [ip_address] => 239.165.115.154
        )
 
 .
 . 
 .    
 
    [9] => Array
        (
            [id] => 10
            [first_name] => Doll
            [last_name] => Mutter
            [email] => dmutter9@tumblr.com
            [gender] => Female
            [ip_address] => 248.64.142.26
        )
 
)

The next step is initializing a SimpleXMLElement object. PHP SimpleXMLElement object represents an XML document and initializes a root element. The root element will include all the child elements as we parse the array.

$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><root></root>')

The new SimpleXMLElement is a syntax for initializing an object of this class. The object now represents an XML document. Observe the constructor function, which helps build up the foundational structure by setting up the XML version and root tag.

Now comes the fun part, the core function of PHP JSON to XML conversion. Ths function expects the JSON array and the SimpleXMLElement and uses a loop and class methods to build up the SimpleXMLObject from the JSON array.

function arraytoXML($json_arr, &$xml)
{
    foreach($json_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 expects a JSON array and a reference to the SimpleXMLElement object. The function includes recursive calls when it encounters nested arrays. The output is a SimpleXMLElement object as an intermediary form.

SimpleXMLElement Object
(
    [Element 0] => SimpleXMLElement Object
        (
            [id] => 1
            [first_name] => Mendie
            [last_name] => Dunnett
            [email] => mdunnett0@usnews.com
            [gender] => Male
            [ip_address] => 239.165.115.154
        )
    .
    .
    .
    [Element 9] => SimpleXMLElement Object
        (
            [id] => 10
            [first_name] => Doll
            [last_name] => Mutter
            [email] => dmutter9@tumblr.com
            [gender] => Female
            [ip_address] => 248.64.142.26
        )
 
)

Finally, using the asXML method on the SimpleXMLElement object, we write out the object to a file as XML. 

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

Here’s the output.

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <Element0>
        <id>1</id>
        <first_name>Mendie</first_name>
        <last_name>Dunnett</last_name>
        <email>mdunnett0@usnews.com</email>
        <gender>Male</gender>
        <ip_address>239.165.115.154</ip_address>
    </Element0>
    <Element1>
        <id>2</id>
        <first_name>Florida</first_name>
        <last_name>Jurn</last_name>
        <email>fjurn1@ihg.com</email>
        <gender>Female</gender>
        <ip_address>3.225.31.136</ip_address>
    </Element1>
    <Element2>
        <id>3</id>
        <first_name>Ingeborg</first_name>
        <last_name>Robinson</last_name>
        <email>irobinson2@aol.com</email>
        <gender>Female</gender>
        <ip_address>42.187.239.40</ip_address>
    </Element2>
    <Element3>
        <id>4</id>
        <first_name>Ariana</first_name>
        <last_name>Ashborn</last_name>
        <email>aashborn3@usatoday.com</email>
        <gender>Non-binary</gender>
        <ip_address>48.25.75.166</ip_address>
    </Element3>
    <Element4>
        <id>5</id>
        <first_name>Melinda</first_name>
        <last_name>Mixture</last_name>
        <email>mmixture4@howstuffworks.com</email>
        <gender>Female</gender>
        <ip_address>177.172.229.237</ip_address>
    </Element4>
    <Element5>
        <id>6</id>
        <first_name>Eulalie</first_name>
        <last_name>Cheves</last_name>
        <email>echeves5@examiner.com</email>
        <gender>Female</gender>
        <ip_address>132.241.220.47</ip_address>
    </Element5>
    <Element6>
        <id>7</id>
        <first_name>Shermie</first_name>
        <last_name>Dedman</last_name>
        <email>sdedman6@google.com</email>
        <gender>Male</gender>
        <ip_address>209.248.152.128</ip_address>
    </Element6>
    <Element7>
        <id>8</id>
        <first_name>Marya</first_name>
        <last_name>Tromans</last_name>
        <email>mtromans7@1und1.de</email>
        <gender>Female</gender>
        <ip_address>175.112.109.52</ip_address>
    </Element7>
    <Element8>
        <id>9</id>
        <first_name>Concordia</first_name>
        <last_name>Cumberledge</last_name>
        <email>ccumberledge8@nhs.uk</email>
        <gender>Female</gender>
        <ip_address>3.189.87.195</ip_address>
    </Element8>
    <Element9>
        <id>10</id>
        <first_name>Doll</first_name>
        <last_name>Mutter</last_name>
        <email>dmutter9@tumblr.com</email>
        <gender>Female</gender>
        <ip_address>248.64.142.26</ip_address>
    </Element9>
</root>

Phew! That was a lot of ground to cover. Let’s put all the pieces together.

<?php
 
$JSON_arr = json_decode($JSON, true);
 
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><root></root>');
 
function arraytoXML($json_arr, &$xml)
{
    foreach($json_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);
        }
    }
}
 
arraytoXML($JSON_arr, $xml);
print_r($xml->asXML('output.xml'));
?>

Perfect! With this, we’re all set for now. Let’s wrap up this article.

Wrap Up

This article demonstrates how to convert JSON to XML in PHP. It follows a step-by-step approach from parsing JSON to a PHP array and then to the PHP SimpleXMLElement object. Finally, it demonstrates how to convert the SimpleXMLElement object to an XML file. We hope you’ve grasped every step of the workflow.

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.

  Was this information helpful?

Can Your Career Use a Boost?

Check out our free PHP developer career guide. We created this guide as a resource to help fellow programmers level up their careers. This is an excellent resource whether you are new to programming or have been a professional for more than 15 years.

Click here to read the guide


Article Categories

Article Tags

© 2022 Confident.Systems