从天气JSON Feed获取数据

时间:2015-04-26 19:40:30

标签: php json

我正试图从api.openweathermap.org获取天气。我可以打印风速,但是当我尝试打印天气时它会给我一个错误,但我正以与风速相同的方式访问它。这是我的代码:

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

$data = file_get_contents('http://api.openweathermap.org/data/2.5/weather?q=London,uk');
$json = json_decode($data);
//This works
echo 'The wind speed is: ' . $json->wind->speed;
//This doesn't work
echo 'The weather is: ' . $json->weather->description;

当我运行它时会发生这种情况:

  

风速为:2.07

     

注意:尝试在C:\ Users \ Mike \ Desktop \ php-中获取非对象的属性   第10行的test.php

     

天气是:

为什么它适用于风速但不适用于天气描述?该元素存在于返回的json中。

2 个答案:

答案 0 :(得分:1)

这是正确的代码

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

$data = file_get_contents('http://api.openweathermap.org/data/2.5/weather?q=London,uk');
$json = json_decode($data);

var_dump($json);
echo 'The wind speed is: ' . $json->wind->speed;
//This doesn't work
echo 'The weather is: ' . $json->weather[0]->description;

为什么您的代码出错,因为天气不是对象。天气是阵列。

如果您var_dump() $ json数据。它将显示详细信息。您还可以在http://api.openweathermap.org/获取天气数据。 []内的数据。这意味着这是一个数组。

object(stdClass)[1]
  public 'coord' => 
    object(stdClass)[2]
      public 'lon' => float -0.13
      public 'lat' => float 51.51
  public 'sys' => 
    object(stdClass)[3]
      public 'message' => float 0.0166
      public 'country' => string 'GB' (length=2)
      public 'sunrise' => int 1430023268
      public 'sunset' => int 1430075724
  public 'weather' => 
    array (size=1)
      0 => 
        object(stdClass)[4]
          public 'id' => int 801
          public 'main' => string 'Clouds' (length=6)
          public 'description' => string 'few clouds' (length=10)
          public 'icon' => string '02n' (length=3)
  public 'base' => string 'stations' (length=8)
  public 'main' => 
    object(stdClass)[5]
      public 'temp' => float 282.349
      public 'temp_min' => float 282.349
      public 'temp_max' => float 282.349
      public 'pressure' => float 1013.66
      public 'sea_level' => float 1021.61
      public 'grnd_level' => float 1013.66
      public 'humidity' => int 79
  public 'wind' => 
    object(stdClass)[6]
      public 'speed' => float 2.07
      public 'deg' => float 33.0002
  public 'clouds' => 
    object(stdClass)[7]
      public 'all' => int 24
  public 'dt' => int 1430076277
  public 'id' => int 2643743
  public 'name' => string 'London' (length=6)
  public 'cod' => int 200

答案 1 :(得分:0)

JSON中的天气是一个数组:

"weather": [
    {
        "id": 801,
        "main": "Clouds",
        "description": "few clouds",
        "icon": "02d"
    }
],

也许你可以做到

 echo 'The weather is: ' . $json->weather[0]->description;