【问题标题】:PHP get data OpenWeatherMapPHP 获取数据 OpenWeatherMap
【发布时间】:2015-10-06 11:02:19
【问题描述】:

我想从OWM API 获取天气数据,在这种情况下我想获取temeraturediscription 信息。我怎么能通过 PHP 从他们的 API 中“拉”这个?

【问题讨论】:

    标签: php api weather-api openweathermap


    【解决方案1】:

    真的很简单,看看这段代码。

    <?php
    
     //get JSON
     $json = file_get_contents('http://api.openweathermap.org/data/2.5/find?q=Calabar,NG&type=accurate&mode=jso‌​n');
    
     //decode JSON to array
     $data = json_decode($json,true);
    
     //show data
     var_dump($data);
    
     //description
     echo $data['weather'][0]['description'];
     //temperature
     echo $data['main']['temp'];
    
    
    ?> 
    

    首先你需要使用function file_get_contents() 获取文件/字符串,在这种情况下它是 JSON 字符串。在您需要使用函数json_decode() 解码此字符串之后。参数 true 表示我们要将此字符串解析为 array 而不是 object。在此操作之后,您可以使用此数据集,因为它是简单的变量类型的数组。就是这样。

    编辑:

    根据下面的Prodigy评论编辑网址

    【讨论】:

    • 太棒了!只剩下一个问题;p。 “echo $data['weather'][0]['description'];”中的“[0]”是什么意思?
    • 它是数组中的索引。他们可能在一些城镇有多个传感器,所以温度可能不同(恕我直言)
    • 我明白了,所以当您放置“[1]”时,您“可能”会出错?
    • 如果索引 1 不存在,你会收到错误,是的。
    • 我认为 OWM URL 改变了一点 http://api.openweathermap.org/data/2.5/weather?q=London 到这样的 http://api.openweathermap.org/data/2.5/find?q=Calabar,NG&amp;type=accurate&amp;mode=json
    【解决方案2】:

    您可以使用 Curl 或 file_get_contents,然后保存其中任何一个的响应。然后解析您正在寻找的值的响应。

    【讨论】:

      猜你喜欢
      • 2018-05-17
      • 2016-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-16
      • 2021-12-31
      • 1970-01-01
      相关资源
      最近更新 更多