Problems using JSON via PHP to access openweather-API

Problems using JSON via PHP to access openweather-API
0

#1

Hello ,

I am trying to access the openweather-API. Most of the data I can access, but just some I can’t - for example the “description”:

$currDataPolled          = file_get_contents("http://api.openweathermap.org/data/2.5/weather?id=2939623&appid=xxxxxxxxxxxxxxx&units=metric&lang=de");
$currUvIndexPolled       = file_get_contents("http://api.openweathermap.org/data/2.5/uvi?appid=xxxxxxxxxx&lat=48.26&lon=11.43");
//parsing
$parsedCurrData          = json_decode($currDataPolled);
$parsedcurrUvIndex       = json_decode($currUvIndexPolled);
//getting values to vars
$location                = $parsedCurrData->{'name'};
$currTemp                = $parsedCurrData->{'main'}->{'temp'};
$currHumid               = $parsedCurrData->{'main'}->{'humidity'};
//$currPressure          = $parsedCurrData->{'main'}->{'pressure'};
$currDescription         = $parsedCurrData->{'weather'}->{'0'}->{'description'};//->{'id'};
$currUv                  = $parsedcurrUvIndex->{'value'};
//outputting
echo $currDescription."<br />\n";

In the webbrowser the API-call results this:

{
  "coord": {
    "lon": 11.43,
    "lat": 48.26
  },
  "weather": [
    {
      "id": 500,
      "main": "Rain",
      "description": "Leichter Regen",
      "icon": "10n"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 16.66,
    "pressure": 1014,
    "humidity": 93,
    "temp_min": 15,
    "temp_max": 18
  },

Is it maybe because of the “[” and “]” ?

Thank your very much!


#2

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


#3

Thank you for editing and the explanation.

In the meantime I found the solution: I did not recognize “weather” as an array. This worked:

$currDescription         = $parsedCurrData->weather[0]->description;