3

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 a json with all this data and use it as a data source.

How can I do it ?

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Nauman
  • 894
  • 4
  • 14
  • 45

2 Answers2

1

The data you posted is not valid JSON. It misses some surrounding and ending brackets.

Ok, let's fix that... 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 the JSON with PHP you can simply load the 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>";
?>
Jens A. Koch
  • 39,862
  • 13
  • 113
  • 141
0

A 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 to use it as a datasource

$myData = json_decode(
    file_get_contents('myJsonFile.json')
);
Mark Baker
  • 209,507
  • 32
  • 346
  • 385