这个问题在这里已经有了答案:





How can I parse a JSON file with PHP? [duplicate]

(16 个回答)


2年前关闭。




我正在尝试使用 PHP 从以下 JSON 文件中获取数据。我特别想要“温度最小值”和“温度最大值”。

这可能真的很简单,但我不知道如何做到这一点。我被困在 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,
            }
        ]
    }
}

最佳答案

使用 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
}

Demo!

关于php - 使用 PHP 从 JSON 文件中获取数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19758954/

10-14 13:03
查看更多