【问题标题】:JSON Weather Feed in PHPPHP 中的 JSON 天气提要
【发布时间】:2016-11-24 04:39:48
【问题描述】:

我正在尝试通过从 PHP 中的 JSON 提要中提取这些天气信息来显示它。我不知道为什么它不打印。这是代码:

$url="http://api.openweathermap.org/data/2.5/forecast?q=Albany,usl&APPID=5099c5feb579c7a17b030de0d009282f&units=metric";
$json=file_get_contents($url);
$data=json_decode($json);



echo '<h1>', $data->name, ' (', $data->sys->country, ')</h1>';

// the general information about the weather
echo '<h2>Temperature:</h2>';
echo '<p><strong>Current:</strong> ', $data->main->temp, '&deg; C</p>';
echo '<p><strong>Min:</strong> ', $data->main->temp_min, '&deg; C</p>';
echo '<p><strong>Max:</strong> ', $data->main->temp_max, '&deg; C</p>';

?>

我的输出是这样的:

()

温度:

电流:°C

最低:°C

最高:°C

【问题讨论】:

  • $data=json_decode($json, false);

标签: php json weather-api openweathermap


【解决方案1】:

解析 API 输出的方式存在问题。检查以下 -

    $url="http://api.openweathermap.org/data/2.5/forecast?q=Albany,usl&APPID=5099c5feb579c7a17b030de0d009282f&units=metric";
    $json=file_get_contents($url);
    $data=json_decode($json);

    echo '<h1>', $data->city->name, ' (', $data->city->country, ')</h1>';

    // the general information about the weather
    echo '<h2>Temperature:</h2>';
    echo '<p><strong>Current:</strong> ', $data->list[0]->main->temp, '&deg; C</p>';
    echo '<p><strong>Min:</strong> ', $data->list[0]->main->temp_min, '&deg; C</p>';
    echo '<p><strong>Max:</strong> ', $data->list[0]->main->temp_max, '&deg; C</p>';

【讨论】:

  • 完美运行,谢谢!
  • 如何访问描述?我在打印其他输出时遇到问题。
  • $data->list[0]-> weather[0]-> 描述
【解决方案2】:

你的结构有误。如果你想看看 json 的结构只是

echo '<pre>',print_r($data,1),'</pre>';

为你输出你想要的

$url="http://api.openweathermap.org/data/2.5/forecast?q=Albany,usl&APPID=5099c5feb579c7a17b030de0d009282f&units=metric";
$json=file_get_contents($url);
$data=json_decode($json);
echo $data->city->name; 

【讨论】:

  • 我知道如何使用 print_r 函数。另外,已经尝试过您的建议并且没有得到任何输出。这是您建议的 print_r 链接:aswanson.net/Weather/weather.php
  • 朋友,你一定有什么问题。我只是在phpfiddle.org 中运行它,它输出 ablany 没有问题。此外,当我转到aswanson.net/Weather/weather.php 时,它的输出也正常。您只是没有看到输出吗?奥尔巴尼(美国) 温度:当前:29.87° C 最低:27.67° C 最高:29.87° C 条件:晴朗的天空 风条件:1.61
猜你喜欢
  • 2011-09-24
  • 2016-07-16
  • 2011-12-14
  • 1970-01-01
  • 1970-01-01
  • 2017-04-12
  • 2021-12-23
  • 1970-01-01
  • 2016-01-27
相关资源
最近更新 更多