-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache_feed.php
More file actions
109 lines (58 loc) · 2.34 KB
/
cache_feed.php
File metadata and controls
109 lines (58 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
header('Access-Control-Allow-Origin: *');
global $city, $state, $weather, $apiFile, $localfile, $epoch, $dataHolder;
//was setting null as placeholder for variable of future function for new city-state lookup
$city = (empty($_POST['city'])) ? null : $_POST['city'];
$state = (empty($_POST['state'])) ? null : $_POST['state'];
$city= strtoupper($city);//convert to uppercase prevent duplication in json
$state= strtoupper($state);
//temp
$city=rawurlencode($city);//deal with spaces for api
$next_update=300;//seconds - how long to wait before next update
$epoch=time();
$apiKey="490b7f6020319ed9";// set API key;
$apiFile="http://api.wunderground.com/api/$apiKey/conditions/q/$state/$city.json";
$localfile="weather_data.json";
$lastTime=null;
$json_decode="";
$dataHolder=array();
if(file_exists($localfile)){
$json_decode=getWeather($localfile);
$weather=checkWeather($json_decode);
}else{
//if file does not exist, seed it
$weather=checkWeather($json_decode);
}
function getWeather($theFile){
$context = stream_context_create(array('http' => array('header'=>'Connection: close\r\n')));
$fileContents= file_get_contents($theFile,false,$context);
$json_decode=json_decode($fileContents,true);
return $json_decode;
}
function checkWeather($json_decode){
global $city, $state, $epoch, $next_update, $apiFile, $dataHolder;
$cityHolder=array();
$lastTime=(empty($json_decode['city'][$city][time])) ? 0 : $json_decode['city'][$city][time];
$updateTime = ($epoch-$next_update>$lastTime) ? 0 : 1;
if(!$updateTime){
//update weather
$tempweather=getWeather($apiFile);
$weather=$tempweather["current_observation"];//["display_location"]["full"];
//capture new data and set into array for adding to json
$cityHolder["time"]=$epoch;
$cityHolder["weather"]=$weather;
$json_decode["city"][$city]=$cityHolder;
updateWeather($json_decode);
}else{
//just pass along weather;
$weather=$json_decode['city'][$city]['weather'];
}
return $weather;
}
function updateWeather($json_decode){
global $localfile;
$newWeather=json_encode($json_decode);
file_put_contents($localfile, $newWeather);
}
echo (json_encode($weather));//send stored json of this city to browser
?>