How to write json file as data source in php?

I have some data like this

"name": "abc",
"adr": "bcd",
"partners": {
            "101": {
                   "name": "xyz.com",
                   "prices": {
                            "1001": {
                            "description": "Single Room",
                            "amount": 125,
                            "from": "2012-10-12",
                            "to": "2012-10-13"
                            },
                            "1002": {
                            "description": "Double Room",
                            "amount": 139,
                            "from": "2012-10-12",
                            "to": "2012-10-13"
                        }
                    }

      

Now I have to write json with all this data and use it as data source.

How can i do this?

+3


source to share


2 answers


The data you posted is not valid JSON. It omits some of the surrounding and trailing brackets.

Ok, fix this ... and save it as data.json

:

{
    "name": "abc",
    "adr": "bcd",
    "partners": {
        "101": {
            "name": "xyz.com",
            "prices": {
                "1001": {
                    "description": "SingleRoom",
                    "amount": 125,
                    "from": "2012-10-12",
                    "to": "2012-10-13"
                },
                "1002": {
                    "description": "DoubleRoom",
                    "amount": 139,
                    "from": "2012-10-12",
                    "to": "2012-10-13"
                }
            }
        }
    }
}

      



To access JSON using PHP, you can simply upload a file and convert the JSON to an array.

<?php 
$jsonFile = "data.json"
$json = file_get_contents($jsonFile);
$data = json_decode($json, TRUE);

echo "<pre>";
print_r($data);
echo "</pre>";
?>

      

+1


source


PHP script to create a file containing this data as json

// the data you need 
$phpData = [
    "name" => "abc",
    "adr" => "bcd",
    "partners" => [
        "101" => [
            "name" => "xyz.com",
            "prices" => [
                "1001" => [
                    "description" => "Single Room",
                    "amount" => 125,
                    "from" => "2012-10-12",
                    "to" => "2012-10-13",
                ],
                "1002" => [
                    "description" => "Double Room",
                    "amount" => 139,
                    "from" => "2012-10-12",
                    "to" => "2012-10-13",
                ]
            ]
        ]
    ]
];

// json_encode() that data to a string
$jsonData = json_encode($phpData);
// write that string to your file
file_put_contents('myJsonFile.json', $jsonData);

      



And use it as a data source

$myData = json_decode(
    file_get_contents('myJsonFile.json')
);

      

0


source







All Articles