03-Apr-2023
.
Admin
Hi Friends,
This article will give you example of how to convert xml data into json in php?. I explained simply about convert xml data to json encoded.
In this post, You'll learn json encoded convert xml data to array php. i will show you use of convert xml data to array php json_encode.
So let's see bellow example:
Example:
<?php
$xml_string = <<<XML
<?xml version='1.0' standalone='yes'?>
<movies>
<movie>
<title>PHP Convert XML Data Into JSON</title>
<characters>
<character>
<name>Ms. Coder</name>
<actor>Piyush Kamani</actor>
</character>
<character>
<name>Mr. Coder</name>
<actor>Nicesnippets</actor>
</character>
</characters>
<plot>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</plot>
<great-lines>
<line>This Is My Web Site Nicesnippets.com</line>
</great-lines>
<rating type="thumbs">7</rating>
<rating type="stars">5</rating>
</movie>
</movies>
XML;
$xml = simplexml_load_string($xml_string);
$jsonData = json_encode($xml, JSON_PRETTY_PRINT); // convert the XML string to JSON
echo '<pre>';
print_r(var_dump($jsonData));
?>
Output:
string(697) "{
"movie": {
"title": "PHP Convert XML Data Into JSON",
"characters": {
"character": [
{
"name": "Ms. Coder",
"actor": "Piyush Kamani"
},
{
"name": "Mr. Coder",
"actor": "Nicesnippets"
}
]
},
"plot": "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
"great-lines": {
"line": "This Is My Web Site Nicesnippets.com"
},
"rating": [
"7",
"5"
]
}
}"
I hope it can help you...
#PHP