如何在php中将json文件写为数据源?

时间:2015-06-21 10:35:59

标签: php mysql json mysqli

我有一些像这样的数据

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

我该怎么做?

2 个答案:

答案 0 :(得分:1)

您发布的数据无效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>";
?>

答案 1 :(得分:0)

用于创建包含此数据的文件的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')
);