function get_weather old FALSE cache_file dirname __FILE__ cache weath

 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
function get_weather() {
$old = FALSE;
$cache_file = dirname(__FILE__) . '/cache/weather.ce';
if (file_exists($cache_file)) {
$cache_data = file_get_contents($cache_file);
$cache_data = unserialize($cache_data);
if ($cache_data[0] < time() - 3600) {
$old = TRUE;
echo "Get new data";
} else {
$temp = $cache_data[1];
echo "From Cache";
}
} else {
$old = TRUE;
}
if ($old) {
$oCurl = curl_init("http://point.md/Weather/Default.aspx");
curl_setopt($oCurl, CURLOPT_HEADER, 0);
curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
$page = curl_exec($oCurl);
curl_close($oCurl);
$mix = '<a href="/Weather/CurrentTemperature/Default.aspx" class="green">';
$pos = strpos($page, $mix);
$page = substr($page, $pos + strlen($mix));
if (!$pos) {
$mix = '<a href="/Weather/CurrentTemperature/Default.aspx" class="blue">';
$pos = strpos($page, $mix);
$page = substr($page, $pos + strlen($mix));
if (!$pos) {
return "*°C";
}
}
$mix = '</a>';
$pos = strpos($page, $mix);
$temp = substr($page, 0, $pos);
# write to cache
$f = fopen($cache_file, 'w+');
flock($f, LOCK_EX);
$cache_data = array(time(), $temp);
fwrite($f, serialize($cache_data));
flock($f, LOCK_UN);
fclose($f);
}
return $temp;
}