How to Convert XML to JSON in PHP

Summary:

Converting an XML string to JSON in PHP can be done in 2 functions. Use the simplexml_load_string to create an object then use json_encode to export into JSON string. See article for details.

Code Snippet: XML to JSON in PHP

This article focuses on converting XML to JSON in PHP. You can convert XML to JSON using 2 functions. Here’s the relevant code snippet to transform XML to JSON.

<?php
$employees_xml =
'&lt;employees>
    &lt;employee  id="1">
        &lt;firstname>Jack&lt;/firstname>
        &lt;lastname>Nesham&lt;/lastname>
        &lt;age>22&lt;/age>
        &lt;role>Software Engineer&lt;/role>
    &lt;/employee>
    &lt;employee id="2">
        &lt;firstname>Maxwell&lt;/firstname>
        &lt;lastname>Rick&lt;/lastname>
        &lt;age>25&lt;/age>
        &lt;role>DevOps Engineer&lt;/role>
    &lt;/employee>
&lt;/employees>';
 
 
$xml = simplexml_load_string($employees_xml);
$json = json_encode($xml, JSON_PRETTY_PRINT);
 
?>

That’s not the only way, though. This is a solid solution in many cases, but you may encounter a more complex situation, need more flexibility, or you need this in several locations. There is a solid 3rd party composer package to convert XML to CSV which we’ll discuss further in the article.

Relevant Content: XML & JSON Conversion

Converting PHP XML to JSON

In the article, “How to convert JSON to XML in PHP”,  we learned about SimpleXMLElement class and json_decode function that helps in JSON to XML transformation. That article also has some basic information about XML and JSON. This article goes the other way – XML to JSON PHP.

So without any further ado, let’s start with the XML to JSON using PHP.

Scenario: Need to convert XML string of employee data to JSON in PHP

Background & Setup: XML String

You are building an integration for your employee management system written in PHP. Your API outputs JSON data but the incoming employee integration is in XML. You need to quickly convert this data into JSON in an efficient and performant manner. How do you do it?

Let’s get setup.

Here’s an example of XML showing a couple of records for employees. This is what a typical XML looks like, but an important thing here is the "id" attribute. We’ll see how JSON accommodates these attributes when we convert from XML to JSON.

&lt;employees>
    &lt;employee  id="1">
        &lt;firstname>Jack&lt;/firstname>
        &lt;lastname>Nesham&lt;/lastname>
        &lt;age>22&lt;/age>
        &lt;role>Software Engineer&lt;/role>
    &lt;/employee>
    &lt;employee id="2">
        &lt;firstname>Maxwell&lt;/firstname>
        &lt;lastname>Rick&lt;/lastname>
        &lt;age>25&lt;/age>
        &lt;role>DevOps Engineer&lt;/role>
    &lt;/employee>
&lt;/employees>

Option 1: Convert XML to JSON string in PHP using JSON function

PHP json_encode is called whenever we need to get JSON representation of data. In JSON to XML, we used json_decode. Let’s see how the JSON encode function works here. The workflow is quite simple as shown in the illustration.

We’ll begin with loading XML string in PHP.

$xml = simplexml_load_string($employees_xml);

This function returns a SimpleXMLElement object. The next step would be encoding it into JSON.

$json = json_encode($xml, JSON_PRETTY_PRINT);

PHP json_encode takes the SimpleXMLElement object and returns JSON. Let’s put this all together and see what the output looks like.

<?php
$employees_xml =
'&lt;employees>
    &lt;employee  id="1">
        &lt;firstname>Jack&lt;/firstname>
        &lt;lastname>Nesham&lt;/lastname>
        &lt;age>22&lt;/age>
        &lt;role>Software Engineer&lt;/role>
    &lt;/employee>
    &lt;employee id="2">
        &lt;firstname>Maxwell&lt;/firstname>
        &lt;lastname>Rick&lt;/lastname>
        &lt;age>25&lt;/age>
        &lt;role>DevOps Engineer&lt;/role>
    &lt;/employee>
&lt;/employees>';
 
 
$xml = simplexml_load_string($employees_xml);
$json = json_encode($xml, JSON_PRETTY_PRINT);
 
?>

For convenience, we have saved the XML string in a variable. You can also read it from a file using the file_get_contents function in PHP. Here’s the JSON output.

{
    "employee": [
        {
            "@attributes": {
                "id": "1"
            },
            "firstname": "Jack",
            "lastname": "Nesham",
            "age": "22",
            "role": "Software Engineer"
        },
        {
            "@attributes": {
                "id": "2"
            },
            "firstname": "Maxwell",
            "lastname": "Rick",
            "age": "25",
            "role": "DevOps Engineer"
        }
    ]
}

Note: Converting XML with Attributes to JSON in PHP

The JSON includes an array of employee objects. Notice that both of these objects have a key “@attributes” and the value is an object with “id”. That’s why we emphasized the attributes in the XML section above. This is something not too obvious for many developers. 

It was necessary to draw your attention to XML attributes to JSON. Next, let’s see another option of XML to JSON.

Option 2: XML to JSON in PHP using Laminas-XML2JSON Composer Package

Laminas is a popular library for enterprise-grade PHP components and MVC framework. Laminas-XML2JSON is a component for converting XML to JSON. To begin with Laminas-XML2JSON we need to install using PHP package manager Composer. Here’s how to download this third-party package.

composer require laminas/laminas-xml2json

We’ll be using the fromXML method defined in the imported class. The function takes two arguments – an XML string and a boolean for XML attributes. If you set it to true, the returned JSON includes the attributes.

Here’s PHP to JSON with example.

<?php
require __DIR__ . '/vendor/autoload.php';
 
$employees_xml =
'&lt;employees>
    &lt;employee  id="1">
        &lt;firstname>Jack&lt;/firstname>
        &lt;lastname>Nesham&lt;/lastname>
        &lt;age>22&lt;/age>
        &lt;role>Software Engineer&lt;/role>
    &lt;/employee>
    &lt;employee id="2">
        &lt;firstname>Maxwell&lt;/firstname>
        &lt;lastname>Rick&lt;/lastname>
        &lt;age>25&lt;/age>
        &lt;role>DevOps Engineer&lt;/role>
    &lt;/employee>
&lt;/employees>';
 
 
$json = Laminas\Xml2Json\Xml2Json::fromXml($employees_xml, false);
?>

The output is similar to what we have seen already. 

That’s all for this article. Let’s wrap it up quickly.

Conclusion: XML to JSON String PHP Conversion

Wrap Up

So, this article is all about XML to JSON. The first example uses JSON encode to convert SimpleXMLElement object to JSON. The second example uses a third-party library Laminas. Laminas include a static function toXML that returns a JSON representation of XML. The article also highlights the XML attributes and how they translate to JSON.

Functions & Packaged Mentioned

simplexml_load_string: (PHP 5, 7, 8) This is a core PHP function that was first introduced in PHP 5. You should be safe to use this function as there is no concern of deprecation in the near future. It is the standard function to load an XML string into PHP.

json_encode: (PHP 5.2+, 7, 8) You will come across this function anytime you need to create a JSON string. It is commonly used to output your REST APIs. This is also a core function and deprecation is unlikely in the near or distant future.

Laminas XML2Json Package: (PHP 8) This XML to JSON conversion package is part of the larger Laminas PHP framework. The Laminas framework is extensively documented and appears to be actively maintained. I don’t have much experience working in this framework but you should be safe to use this package. I generally consider forking 3rd party packages where I feel comfortable with the current version code but unsure what may happen in future iterations. This package contains several helper functions that can make XML & JSON conversion easier.

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