How to use the OpenWeatherMap API using PHP ?
In, this tutorial we are going to discuss OpenWeatherMap API key, to fetch weather data from different countries.
In order to fetch the data we need an API key, Just go to the website of OpenWeatherMap and create a new account then get the API Key.
Before making an API call please make sure you get the City Name, State Code, and Country code to fetch the data.
e.g city name = Delhi , state code = IN, country code = IN
The following URL is used to fetch the data, we are assuming that you have your own credentials (API Key) e.g appid=d62ca415a6b61d8927e6d87b8c42
http://api.openweathermap.org/data/2.5/weather?q={city name},{state code},{country code}&appid={API key}
Table of Contents
As mentioned above let’s fill the URL with required data, e.g shown below:
http://api.openweathermap.org/data/2.5/weather?q=Delhi,IN,IN&appid=d62ca415a6b61d8927e6d87b8c42
The format of the data is given in the following format:
mode=json (default)
mode=xml
If you want to change the data format then you need to add the mode in the URL as “http://api.openweathermap.org/data/2.5/weather?q=Delhi,IN,IN&mode=xml&appid= d62ca415a6b61d8927e6d87b8c42″, it will return the data in XML format.
Create PHP file and write the following code of openweathermap API
Now, we have a working URL that helps to fetch the data using PHP, Let’s move on PHP part. First, we need to create a function to fetch the data through these URL, the function used cURL as shown below using in PHP code:
function WeatherUrl($url){
$cn = curl_init();
curl_setopt($cn, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($cn, CURLOPT_URL, $url); // get the contents using url
$weatherdata = curl_exec($cn); // execute the curl request
curl_close($cn); //close the cURL
return $weatherdata;
}
Create a variable named $url, and assign the URL which created before, then call the WeatherUrl() function with argument $url to get the data as mentioned below:
$url="http://api.openweathermap.org/data/2.5/weather?q=Delhi,IN,IN&units=metric&appid=d62ca415a6b61d8927e6d87b8c420";
$response=WeatherUrl($url);
To extract the data from json_file we need to create a JSON object, to do this we need to call the json_decode function and pass the $response.
$data = json_decode($response);
$temp = $data->main->temp . '℃';
$minimum_temp = $data->main->temp_min . '℃';
$maximum_temp = $data->main->temp_max . '℃';
$feels_like = $data->main->feels_like . '℃';
$pressure = $data->main->pressure . '℃';
$humidity = $data->main->humidity . '℃';
Now, use echo to print the data as :
echo '
Temperature : '. $temp;
echo '
Minimum Temperature : '. $minimum_temp;
echo '
Maximum Temperature : '. $maximum_temp;
echo '
Feels Like : '. $feels_like;
echo '
Pressure : '. $pressure;
echo '
Humidity : '. $humidity;
Output
Temperature : 14.05℃
Minimum Temperature : 12℃
Maximum Temperature : 16.11℃
Feels Like : 12.49℃
Pressure : 1014℃
Humidity : 94℃
Leave a Reply