Get latest Update ! Subscribe Now !

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

As mentioned above let's fill the URL with required data, e.g shown below:

The format of the data is given in the following format:

mode=json (default)


If you want to change the data format then you need to add the mode in the URL as ",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:

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:

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.

Now, use echo to print the data as :

Output :

Click to Get Full Code