Skip to content
Home » How to Convert JSON to XML with PHP Code Examples in 2023

How to Convert JSON to XML with PHP Code Examples in 2023

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.

Converting JSON to XML in PHP Code Example

<?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.

PHP Fundamentals Recommendations

This article is part of our content on PHP Fundamentals. It includes the core concepts that build upon the foundation of writing high-quality PHP code. If you are looking to grow your PHP development abilities. Check out the following recommended affiliate resources. We do make a commission if you do choose to buy through our links. It is one of the ways that help support our mission here at FuelingPHP.

Book: Fundamentals of Web Development

This book is for you if you are starting to learn how to build websites. It is more than just an “intro to programming” book. You will learn the concepts and tips on what goes into creating a high-quality website. Today’s websites are more than text on a screen. They are highly complex applications that encourage user experience. Learn the fundamentals of good web development with this book.

Check it out on Amazon

Book: Programming in PHP (O’Reilly)

O’Reilly should not need any introduction. They are the top publishers when it comes to books on programming and technology. This book fits well within their vast library. If you are newer to the PHP language or want to keep a solid reference by your side. I highly recommend this book for your collection.

Check it out on Amazon

Book: Design Patterns in PHP

I highly recommend this book to any intermediate-level web developer. It takes the theories and best practices of writing high-quality code via design patterns and applies them to PHP. It is a great resource to take your career to the next level

Check it out on Amazon

Video Course: PHP Fundamentals (Pluralsight)

Want to quickly learn PHP? This PHP Fundamentals course is ideal for beginner PHP developers. It is a deep dive into the concepts, structures and well “fundamentals” of PHP development. It includes high-quality video & interactive resources that teach you really fast. I highly recommend this if you are getting started in your PHP journey.

Click here for a 10-day free trial to Pluralsight

Complete Learning Path: Web Development (Pluralsight)

You should definitely check out this learning path from Pluralsight. They have a huge list of video courses, training, and interactive lessons on growing your web development career. You get access to the full library of hundreds of resources for a single monthly subscription. It truly is like Netflix for your career.

Click here to see details (10-day free trial included)

Converting JSON to XML using PHP

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.