PHP Convert XML to JSON Example

PHP

Nicesnippets

839

23-07-2021


Hi Guys,

In this exmple,I will learn you how to convert xml to json in php.you can easy and simply convert xml to json in php

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.

Add Simple Xml File:


PHP Code:

<?php

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

$jsonData = json_encode($xmlObject, JSON_PRETTY_PRINT);

print_r($jsonData);

?>

Output:

{

"CD": [

{

"TITLE": "dill diya galla",

"ARTIST": "Arijit singh",

"COUNTRY": "India",

"COMPANY": "tseries",

"PRICE": "10.90",

"YEAR": "2018"

},

{

"TITLE": "Saiyara",

"ARTIST": "Atif Aslam",

"COUNTRY": "Uk",

"COMPANY": "Records",

"PRICE": "9.90",

"YEAR": "2015"

},

{

"TITLE": "Khairiyat",

"ARTIST": "Sonu nigam",

"COUNTRY": "india",

"COMPANY": "radio",

"PRICE": "9.90",

"YEAR": "2019"

},

{

"TITLE": "all is well",

"ARTIST": "Amir Khan",

"COUNTRY": "pak",

"COMPANY": "Virgin records",

"PRICE": "10.20",

"YEAR": "2012"

},

{

"TITLE": "rockstar",

"ARTIST": "kk",

"COUNTRY": "india",

"COMPANY": "Eros",

"PRICE": "9.90",

"YEAR": "2014"

}

]

}

i hope it can help you...