-3

I am using the OpenWeather API. I saved it in $jsonobj, but don't know how to access weather details. I don't know how [] and {} differs and what they actually mean.

My code is here:

<?php
    $name_of_city = "mathura";
    $request = 'http://api.openweathermap.org/data/2.5/weather?APPID=my_key&q='.$name_of_city;
    $response  = file_get_contents($request);
    $jsonobj  = json_decode($response,true);
    print_r($jsonobj);
?>

enter image description here

ssc-hrep3
  • 15,024
  • 7
  • 48
  • 87
Vivek Gautam
  • 183
  • 1
  • 1
  • 10
  • 4
    Possible duplicate of [Parsing JSON file with PHP](http://stackoverflow.com/questions/4343596/parsing-json-file-with-php) – u_mulder Jan 30 '17 at 11:49
  • 1
    Please don't YELL, and please avoid posting textual information as an image. Images aren't searchable, can't be copied-and-pasted, and offer poor accessibility. And please **_never_** post a text image as a JPEG. That's a horrible format for text. If you absolutely must post an image of text, use a PNG. – ChrisGPT was on strike Jan 30 '17 at 11:51

2 Answers2

0

[] represents arrays and {} represents objects, so in your example you have for example an object which contains an array of objects named 'weather' , to access is in PHP after json_decode you can go as simple as :

foreach($jsonobj->weather as $weather){
    echo "$weather->main : $weather->description";
}
mrbm
  • 2,164
  • 12
  • 11
  • It show error Notice: Trying to get property of non-object in C:\wamp64\www\localite\index.php on line 9 I just tried here my codeweather as $weather) { echo "$weather->main : $weather->description"; } ?> – Vivek Gautam Jan 30 '17 at 11:55
  • that's because you're telling json_decode to provide you with an associative array instead of objects, simply change json_decode($response,true); to json_decode($response); or use $weather['main'] instead of $weather->main – mrbm Jan 30 '17 at 12:11
0

When you do

json_decode($response,true);

It converts the json to array so you can access it like below:

$name_of_city = "mathura";
$request = 'http://api.openweathermap.org/data/2.5/weather?APPID=my_key&q='.$name_of_city;
$response  = file_get_contents($request);
$jsonobj  = json_decode($response,true);
foreach($jsonobj['weather'] as $weather){
    echo $weather['main'] .":". $weather['description'];//Clear:clear sky
}
Suchit kumar
  • 11,809
  • 3
  • 22
  • 44