使用PHP从JSON文件获取数据

Har*_*unn 103 php json

我正在尝试使用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,
            }
        ]
    }
}
Run Code Online (Sandbox Code Playgroud)

Ama*_*ali 251

使用以下命令获取JSON文件的内容file_get_contents():

$str = file_get_contents('http://example.com/example.json/');
Run Code Online (Sandbox Code Playgroud)

现在使用json_decode()以下方法解码JSON :

$json = json_decode($str, true); // decode the JSON into an associative array
Run Code Online (Sandbox Code Playgroud)

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

echo '<pre>' . print_r($json, true) . '</pre>';
Run Code Online (Sandbox Code Playgroud)

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

$temperatureMin = $json['daily']['data'][0]['temperatureMin'];
$temperatureMax = $json['daily']['data'][0]['temperatureMax'];
Run Code Online (Sandbox Code Playgroud)

或者你想要循环遍历数组:

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

演示!

  • @JonnyNineToes:尝试在脚本的最顶部设置`header('charset = utf8');` (2认同)

Ind*_*ngh 10

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/>';
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)


Gui*_*ehn 9

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

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