Search code examples
phpopenweathermapweather-api

PHP get data OpenWeatherMap


I want to get the weather data from the OWM API, in this case I would like to get the temerature and the discription info. How could I "pull" this from their API via PHP?


Solution

  • It is really simple, check this code.

    <?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'];
    
    
    ?> 
    

    Fist you need to get file/string with function file_get_contents(), in this case it is JSON string. After you need to decode this string with function json_decode(). Parameter true means that we want to parse this string to array instead of object. After this actions you can work with this dataset as it is simple variable type of array. That's all.

    EDIT:

    Edited URL based on Prodigy comment below