使用PHP从JSON文件获取数据

135

我正在尝试使用PHP从以下JSON文件获取数据。我特别想要"temperatureMin"和"temperatureMax"。

这可能非常简单,但是我不知道如何做。我卡在了file_get_contents("file.json")之后该怎么办。希望能得到一些帮助!

{
    "daily": {
        "summary": "No precipitation for the week; temperatures rising to 6° on Tuesday.",
        "icon": "clear-day",
        "data": [
            {
                "time": 1383458400,
                "summary": "Mostly cloudy throughout the day.",
                "icon": "partly-cloudy-day",
                "sunriseTime": 1383491266,
                "sunsetTime": 1383523844,
                "temperatureMin": -3.46,
                "temperatureMinTime": 1383544800,
                "temperatureMax": -1.12,
                "temperatureMaxTime": 1383458400,
            }
        ]
    }
}
3个回答

315
使用 file_get_contents() 获取 JSON 文件的内容:
$str = file_get_contents('http://example.com/example.json/');

现在使用json_decode()函数解码JSON数据:
$json = json_decode($str, true); // decode the JSON into an associative array

您有一个包含所有信息的关联数组。要找到如何访问所需的值,您可以执行以下操作:

echo '<pre>' . print_r($json, true) . '</pre>';

这将以易读的格式打印出数组的内容。请注意,第二个参数设置为true,以便让print_r()知道应该返回输出结果(而不仅仅是打印到屏幕上)。然后,您可以这样访问所需的元素:
$temperatureMin = $json['daily']['data'][0]['temperatureMin'];
$temperatureMax = $json['daily']['data'][0]['temperatureMax'];

或以任何您希望的方式循环遍历数组:

foreach ($json['daily']['data'] as $field => $value) {
    // Use $field and $value here
}

演示!


谢谢!但是我在JSON中似乎遇到了度符号的问题,我做错了什么吗? - Harold Dunn
1
本周没有降水;周二气温升至6°。 - Harold Dunn
1
@HaroldDunn 你能分享一下你的解决方案吗?我怀疑我可能遇到了类似的问题... - user1762633
2
@JonnyNineToes:尝试在脚本的最顶部设置header('charset=utf8'); - Amal Murali
1
@FrayneKonok:他们可能会对“1”感到困惑。我认为最好演示正确的方法。现在我也添加了有关第二个参数的注释。 - Amal Murali
显示剩余5条评论

13
Try:
$data = file_get_contents ("file.json");
        $json = json_decode($data, true);
        foreach ($json as $key => $value) {
            if (!is_array($value)) {
                echo $key . '=>' . $value . '<br/>';
            } else {
                foreach ($value as $key => $val) {
                    echo $key . '=>' . $val . '<br/>';
                }
            }
        }

1
三维、四维等数组怎么办?此外,OP并没有要求输出结果。 - vladkras

13

使用 json_decode 将您的 JSON 转换为 PHP 数组。示例:

$json = '{"a":"b"}';
$array = json_decode($json, true);
echo $array['a']; // b

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接