Skip to content
Home » Convert XML to JSON Correctly With PHP Code Examples (2023)

Convert XML to JSON Correctly With PHP Code Examples (2023)

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.

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)

Want more reviews? Check out our HUGE list of Beginner Web Development Books We’ve Researched and Reviewed for you.

Using JSON in PHP Article Series

Learn the Fundamentals of Good Web Development

Please take a moment and sign up for our free email course on the fundamentals of good web development. Every week is packed with a roundup of articles on our site and from around the web, where we go deep into developing exceptional web applications. We have meetups, code reviews, slack chats, and more.

Click here to get started