使用 PHP 从 JSON 文件中获取数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19758954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get data from JSON file with PHP
提问by Harold Dunn
I'm trying to get data from the following JSON file using PHP. I specifically want "temperatureMin" and "temperatureMax".
我正在尝试使用 PHP 从以下 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!
这可能真的很简单,但我不知道如何做到这一点。我被困在 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,
}
]
}
}
回答by Amal Murali
Get the content of the JSON file using file_get_contents()
:
使用以下命令获取 JSON 文件的内容file_get_contents()
:
$str = file_get_contents('http://example.com/example.json/');
Now decode the JSON using json_decode()
:
现在使用json_decode()
以下方法解码 JSON :
$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>';
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:
这将以一种很好的可读格式打印出数组的内容。请注意,将第二个参数设置为true
是为了让您print_r()
知道应该返回输出(而不仅仅是打印到屏幕)。然后,您可以访问所需的元素,如下所示:
$temperatureMin = $json['daily']['data'][0]['temperatureMin'];
$temperatureMax = $json['daily']['data'][0]['temperatureMax'];
Or loop through the array however you wish:
或者根据需要循环遍历数组:
foreach ($json['daily']['data'] as $field => $value) {
// Use $field and $value here
}
回答by Indrajeet Singh
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/>';
}
}
}
回答by Guilherme Sehn
Use json_decodeto transform your JSON into a PHP array. Example:
使用json_decode将您的 JSON 转换为 PHP 数组。例子:
$json = '{"a":"b"}';
$array = json_decode($json, true);
echo $array['a']; // b