如何在php中编写json文件作为数据源


how to write a json file as a datasource in php?

我有一些类似的数据

"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,并将其用作数据源。

我该怎么做?

您发布的数据不是有效的JSON。它漏掉了一些环绕括号和结束括号。

好的,让我们解决这个问题。。。并保存为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"
                }
            }
        }
    }
}

要使用PHP访问JSON,只需加载文件并将JSON转换为数组即可。

<?php 
$jsonFile = "data.json"
$json = file_get_contents($jsonFile);
$data = json_decode($json, TRUE);
echo "<pre>";
print_r($data);
echo "</pre>";
?>

一个PHP脚本,用于创建一个包含此数据的文件作为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);

并将其用作数据源

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