使用PHP从JSON文件获取数据
我试图使用PHP从以下JSON文件中获取数据。我特别想要“temperatureMin”和“temperatureMax” 这可能真的很简单,但我不知道怎么做。我被困在文件获取内容(“file.json”)之后该做什么。我们将非常感谢您的帮助使用PHP从JSON文件获取数据,php,json,Php,Json,我试图使用PHP从以下JSON文件中获取数据。我特别想要“temperatureMin”和“temperatureMax” 这可能真的很简单,但我不知道怎么做。我被困在文件获取内容(“file.json”)之后该做什么。我们将非常感谢您的帮助 { "daily": { "summary": "No precipitation for the week; temperatures rising to 6° on Tuesday.", "icon": "cle
{
"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,
}
]
}
}
用于将JSON转换为PHP数组。例如:
$json = '{"a":"b"}';
$array = json_decode($json, true);
echo $array['a']; // b
使用以下命令获取JSON文件的内容: 现在使用以下代码解码JSON: 您有一个包含所有信息的关联数组。要了解如何访问所需的值,可以执行以下操作:
echo '<pre>' . print_r($json, true) . '</pre>';
或按您的意愿在阵列中循环:
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/>';
}
}
}
试试:
$data=file_get_contents(“file.json”);
$json=json_decode($data,true);
foreach($json作为$key=>$value){
如果(!是_数组($value)){
回显$key.'=>'.$value.'
';
}否则{
foreach($key=>$val的值){
回显$key.'=>'.$val.
;
}
}
}
谢谢!但我似乎对JSON中的度符号有问题,我做错了什么吗?“本周无降水;周二气温上升到6度。”包括度符号(°)。当我在我的网站上尝试时,这似乎导致您的演示没有任何回音。@HaroldDunn想分享您的解决方案吗?我怀疑我可能有类似的问题…@JonnyNineToes:尝试设置header('charset=utf8')代码>在脚本的最顶端。@FrayneKonok:他们会对1
感到困惑。我认为最好展示一下正确的方法。我还添加了关于第二个参数的注释。关于三、四等维度数组呢?另外,OP并没有要求回显结果
echo '<pre>' . print_r($json, true) . '</pre>';
$temperatureMin = $json['daily']['data'][0]['temperatureMin'];
$temperatureMax = $json['daily']['data'][0]['temperatureMax'];
foreach ($json['daily']['data'] as $field => $value) {
// Use $field and $value here
}
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/>';
}
}
}