How to convert XML to JSON in PHP?

How to convert XML to JSON in PHP?

Hello Devs,

Today, we are going to learn, how to convert XML to JSON in PHP? This tutorials goes into details about to convert XML data into JSON object with PHP. I will show you how you can convert XML into JSON in PHP language? We will see, how to get XML data from XML file and convert into JSON data.

So let's get started. 

Step 1: XML FILE

First you need a XML file. You can create it or download XML sample file as like below. 

Blog Images

 

Step 2: Convert XML into JSON

Now you can convert your XML file into JSON file.

<?php
    $xmlObject = simplexml_load_file('sample.xml');
    $jsonData = json_encode($xmlObject, JSON_PRETTY_PRINT);
      
    print_r($jsonData);
?>

You will see the following output

{

    "food": [

        {

            "name": "Belgian Waffles",

            "price": "$5.95",

            "description": "Two of our famous Belgian Waffles with plenty of real maple syrup",

            "calories": "650"

        },

        {

            "name": "Strawberry Belgian Waffles",

            "price": "$7.95",

            "description": "Light Belgian waffles covered with strawberries and whipped cream",

            "calories": "900"

        },

        {

            "name": "Berry-Berry Belgian Waffles",

            "price": "$8.95",

            "description": "Light Belgian waffles covered with an assortment of fresh berries and whipped cream",

            "calories": "900"

        },

        {

            "name": "French Toast",

            "price": "$4.50",

            "description": "Thick slices made from our homemade sourdough bread",

            "calories": "600"

        },

        {

            "name": "Homestyle Breakfast",

            "price": "$6.95",

            "description": "Two eggs, bacon or sausage, toast, and our ever-popular hash browns",

            "calories": "950"

        }

    ]

}

You can create a JSON file also instead of printing output data. Just replace the following line with print_r($jsonData);. It will create a sample.json file and put the output in that file. 

...

file_put_contents('sample.json',$jsonData);

 

I hope it will help you. 

Happy Coding :)

Leave a Comment

Your email address will not be published. Required fields are marked *

Go To Top
×