ItSolutionStuff.com

PHP Convert XML to JSON Example

By Hardik Savani β€’ May 14, 2024
PHP

Hello,

This tutorial will give you example of php xml to json. you'll learn php convert xml to json array. This post will give you simple example of php xml to json with attributes. i would like to share with you php xml file to json. Alright, let’s dive into the steps.

In this example, i will give you very simple example of convert xml to json array in php. so here, we will keep one simple example file and convert into php array.

Let's see now:

Add Simple Xml File:

you can create or download simple xml file as like bellow:

Download XML Demo File

PHP Code:

now you can see how convert xml to array using bellow code:

<?php

$xmlObject = simplexml_load_file('sample.xml');

$jsonData = json_encode($xmlObject, JSON_PRETTY_PRINT);

print_r($jsonData);

?>

you will see bellow output:

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 check with this code.

i hope it can help you...

Tags: PHP
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

πŸ“Ί Subscribe on YouTube

We Are Recommending You

β˜…

PHP Move File from One Folder to Another Example

Read Now β†’
β˜…

PHP Remove Directory and Files in Directory Example

Read Now β†’
β˜…

PHP Create Directory If It Doesn't Exist Example

Read Now β†’
β˜…

PHP CURL Post Request with Parameters Example

Read Now β†’
β˜…

How to Integrate Google Recaptcha with PHP Form?

Read Now β†’
β˜…

PHP CKEditor with Image Upload using KCFinder Example

Read Now β†’
β˜…

PHP Check Word Exist in String or Not Example

Read Now β†’
β˜…

Mediafire PHP File Uploading and Get Link Example

Read Now β†’
β˜…

How to Convert Object into Array in PHP?

Read Now β†’
β˜…

How to Count Number of Files in a Directory in PHP?

Read Now β†’
β˜…

How to Remove Null Values from Array in PHP?

Read Now β†’