Skip to content

Instantly share code, notes, and snippets.

@maietta
Created June 14, 2016 23:30
Show Gist options
  • Save maietta/39efea36d0164b89d5fa0227e0e966ec to your computer and use it in GitHub Desktop.
Save maietta/39efea36d0164b89d5fa0227e0e966ec to your computer and use it in GitHub Desktop.
NOAA/Weather Widget Startpoint (with simple cache mechanism)
<?php
$cache_file = "/home/cpaneluser/public_html/weather.json";
if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 60 * 5 ))) {
// Cache file is less than five minutes old.
// Don't bother refreshing, just use the file as-is.
$file = file_get_contents($cache_file);
} else {
// Our cache is out-of-date, so load the data from our remote server,
// and also save it over our cache for next time.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://forecast.weather.gov/MapClick.php?lat=41.75&lon=-124.2&unit=0&lg=english&FcstType=json");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
$file = curl_exec($ch);
curl_close($ch);
file_put_contents($cache_file, $file, LOCK_EX);
}
$data = (object) json_decode($file, true);
// header("Content-type: text/plain");
// print_r($data);
echo '<img src="http://forecast.weather.gov/newimages/medium/'.$data->currentobservation['Weatherimage'].'" />';
echo $data->currentobservation['Temp'] . '&deg;F / ';
echo $data->currentobservation['Weather'];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment