使用PHP从JSON文件获取数据 [英] Get data from JSON file with PHP

查看:640
本文介绍了使用PHP从JSON文件获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to get data from the following JSON file using PHP. I specifically want "temperatureMin" and "temperatureMax".

这可能真的很简单,但是我不知道该怎么做.我被困在file_get_contents("file.json")之后该做什么.一些帮助将不胜感激!

It's probably really simple, but I have no idea how to do this. I'm stuck on what to do after file_get_contents("file.json"). Some help would be greatly appreciated!

{
    "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,
            }
        ]
    }
}

推荐答案

使用 file_get_contents() :

$str = file_get_contents('http://example.com/example.json/');

现在使用 json_decode()

$json = json_decode($str, true); // decode the JSON into an associative array

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

You have an associative array containing all the information. To figure out how to access the values you need, you can do the following:

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

这将以一种易于阅读的格式打印出数组的内容.请注意,第二个参数设置为true以便让print_r()知道应该对输出进行返回(而不是仅仅打印到屏幕上).然后,您可以访问所需的元素,如下所示:

This will print out the contents of the array in a nice readable format. Note that the second parameter is set to true in order to let print_r() know that the output should be returned (rather than just printed to screen). Then, you access the elements you want, like so:

$temperatureMin = $json['daily']['data'][0]['temperatureMin'];
$temperatureMax = $json['daily']['data'][0]['temperatureMax'];

或根据需要遍历数组:

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

演示!

这篇关于使用PHP从JSON文件获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆