How To Make Weather API for Websites


1. Make a folders called “api”, “cache”, “weather

2. Now Make a file called “weather.php” inside folder “api”.

3. write the below code “weather.php

weather.php

date_default_timezone_set('Asia/Dubai');

$date = date(‘Y-m-d’) ;
$file_name_timestamp = strtotime($date);

$filename = $_SERVER[‘DOCUMENT_ROOT’].’/api/cache/weather/’.$file_name_timestamp.’.php’;
$weather_data=”;
if (!file_exists($filename)) {
$weather_json = file_get_contents(‘http://api.openweathermap.org/data/2.5/weather?q=Dubai,UAE’);
$weather = json_decode($weather_json);

$output = array(
“temp” => $weather->main->temp – 273.15,
“city” => $weather->name,
“country” => $weather->sys->country,
“weather_info” => $weather->weather[0]->main,
“weather_desc” => $weather->weather[0]->description,
“image” => $weather->weather[0]->icon
);

$ourFileName = “$file_name_timestamp.php”;
$ourFileHandle = fopen($_SERVER[‘DOCUMENT_ROOT’].’/api/cache/weather/’.$ourFileName, ‘w’) or die(“can’t open file”);
fclose($ourFileHandle);
file_put_contents($_SERVER[‘DOCUMENT_ROOT’].’/api/cache/weather/’.$ourFileName,serialize($output));
}
$weather_data = unserialize(file_get_contents($filename));
if(is_array($weather_data)){
$weather_data = json_encode($weather_data);
}
echo $weather_data;

4. Now call that page through a script from that page where the api is needed and the script code is written below.

Script Code

<script>

$.ajax({

url: “/api/weather.php”,

success: function(data){

var x = eval(‘(‘ + data + ‘)’);

//below # are the ID’s of respective field’s ID

$(‘#temperature’).html(x.temp);

$(‘#weatherImg’).attr(‘src’,’/image/weather/’+x.image+’.png’);

$(‘#city’).html(x.city);

$(‘#country’).html(x.country);

}

});

</script>

And Its Done!

Tagged with: , ,
Posted in Mixz Tricks, PHP

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow me on Twitter

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 442 other followers

%d bloggers like this: