How to convert xml to json using php?

by tressie.damore , in category: PHP General , 10 months ago

How to convert xml to json using php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , 10 months ago

@tressie.damore 

You can convert XML to JSON using the built-in functions in PHP. Here's an example of how you can do it:


Assuming you have an XML string or XML file, you can use the simplexml_load_string() or simplexml_load_file() functions to load the XML data into an object.


Once you have the XML object, you can convert it to JSON using the json_encode() function. Optionally, you can use the json_encode() function with the JSON_PRETTY_PRINT option to format the JSON output for better readability.


Here's a code example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// Load XML from a string
$xmlString = '
<root>
  <name>John Doe</name>
  <age>30</age>
</root>
';

$xml = simplexml_load_string($xmlString);

// Convert XML to JSON
$json = json_encode($xml, JSON_PRETTY_PRINT);

echo $json;


This will output the following JSON:

1
2
3
4
{
    "name": "John Doe",
    "age": "30"
}


If you have an XML file, you can use the simplexml_load_file() function to load the XML data into an object. Here's an example:

1
2
3
4
5
6
7
8
// Load XML from a file
$xmlFile = 'data.xml';
$xml = simplexml_load_file($xmlFile);

// Convert XML to JSON
$json = json_encode($xml, JSON_PRETTY_PRINT);

echo $json;


Make sure to replace 'data.xml' with the path to your XML file.


By following these steps, you can easily convert XML to JSON using PHP.