Email me when it's more than 30% likely to rain soon... Pop it into cron once daily and forget. A simple and practical example of working with NOAA/weather.com DWML feeds in PHP
<?php | |
$email = "me@example.com"; | |
// To find your weather feed.... | |
// * Go here: http://forecast.weather.gov/MapClick.php?lat=37.7749295&lon=-122.41941550000001#.UdpHAj7714E | |
// * Search for your location (upper left side of the page as of 7/7/2013) | |
// * Click the orange "XML" button/link (on the right hand side, beneath the first map as of the same date) | |
$feed = 'http://forecast.weather.gov/MapClick.php?lat=39.01000&lon=-96.28&unit=0&lg=english&FcstType=dwml'; | |
// Times are relative so it doesn't matter what you put here... | |
// this is mainly in case you get warnings about TZ settings | |
date_default_timezone_set("UTC"); | |
// Ugly hack to give me a more or less simple native data structure to work with. Because I wanted something | |
// now more than something perfect... For this kind of toy one hour project... | |
$data = json_decode( json_encode( simplexml_load_file( $feed ) ) ); | |
$time_layouts = array(); | |
foreach( $data->data[0]->{"time-layout"} as &$layout ) | |
$time_layouts[$layout->{"layout-key"}] = $layout; | |
$pop = $data->data[0]->{"parameters"}->{"probability-of-precipitation"}; | |
$pop_time_layout = $pop->{"@attributes"}->{"time-layout"}; | |
$likely = 0; | |
$report = ""; | |
foreach( $pop->{"value"} as $idx => $val ) { | |
$ts = strtotime( $time_layouts[$pop_time_layout]->{"start-valid-time"}[$idx] ); | |
if ( ( intval( date( "H", $ts ) ) - 12 ) < 0 ) | |
$tod = "AM"; | |
else | |
$tod = "PM"; | |
if ( !is_string( $val ) ) | |
$this_pop = 0; | |
else | |
$this_pop = intval( $val ); | |
if ( $this_pop > 30 ) | |
$likely++; | |
$report .= sprintf( | |
"%10s %s, %s %2d %3d%%\n", | |
date( "l", $ts ), | |
$tod, | |
date( "M", $ts ), | |
date( "j", $ts ), | |
$this_pop | |
); | |
} | |
if ( $likely ) { | |
mail( | |
$email, | |
'Looks like rain...', | |
sprintf( | |
"<a href='%s'>Details</a><br/><pre>%s</pre>", | |
sprintf( | |
"http://forecast.weather.gov/MapClick.php?lat=%s&lon=%s", | |
$data->{"data"}[0]->location->point->{"@attributes"}->latitude, | |
$data->{"data"}[0]->location->point->{"@attributes"}->longitude | |
), | |
$report | |
), | |
"Content-type: text/html; charset=utf8" | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment