PHP Convert XML Data Into JSON Example


Share:
Published By: Admin, Published On: Jan 11, 2022, Category: PHP


Hello Friends,

This article will give you example of php convert xml to json example. I explained simply about how to convert xml data into json using php. This tutorial will give you simple example of php convert xml to json.

In this post, you'll learn convert xml to json in php. i will show you simple xml to json with php.

Here i will give you many example of how to convert xml to json example php.

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"

        ]

    }

}"

It will help you...

Share: