﻿{"id":1316,"date":"2013-02-21T20:55:13","date_gmt":"2013-02-21T19:55:13","guid":{"rendered":"http:\/\/www.flapane.com\/blog\/?p=1316"},"modified":"2015-03-23T19:36:52","modified_gmt":"2015-03-23T18:36:52","slug":"howto-usare-le-api-di-wunderground-esempio-pratico","status":"publish","type":"post","link":"https:\/\/www.flapane.com\/blog\/2013\/02\/howto-usare-le-api-di-wunderground-esempio-pratico\/","title":{"rendered":"HOWTO: Usare le API di Wunderground &#8211; esempio pratico"},"content":{"rendered":"<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-1317 image\" src=\"https:\/\/www.flapane.com\/blog\/wp-content\/uploads\/2013\/01\/weather_underground_logo.png\" alt=\"weather_underground_logo\" width=\"225\" height=\"135\" \/><\/p>\n<p><span style=\"color: #ff0000;\">(last update del Dicembre 2014: aggiunta la possibilit\u00e0 di mostrare anche le previsioni del giorno, con tanto di riassunto ed icona delle condizioni meteo.)<\/span><\/p>\n<p><a href=\"http:\/\/www.wunderground.com\/\" target=\"_blank\">Weather Underground<\/a> \u00e8 un utilissimo <strong>sito di meteorologia<\/strong>, che consulto da una decina di anni, che rileva in tempo reale le <strong>condizioni atmosferiche<\/strong> e ne trae delle previsioni.<\/p>\n<p>La affidabilit\u00e0 \u00e8 garantita dalle tante stazioni meteo degli appassionati che inviano i loro dati al sito, e che sono installate proprio in zona.<\/p>\n<p>La particolarit\u00e0, molto comoda per chi possiede un sito, \u00e8 che mette anche a disposizione delle <strong>comode API per poter interagire con i dati<\/strong> e poter, per esempio, riportare in tempo reale la temperatura di una stazione meteo, direttamente sul proprio sito, o magari le previsioni per una determinata localit\u00e0.<!--more--><\/p>\n<p>Per prima cosa, andiamo su <a title=\"Wunderground API\" href=\"http:\/\/www.wunderground.com\/weather\/api\/\" target=\"_blank\">http:\/\/www.wunderground.com\/weather\/api\/<\/a> e registriamoci (utilizzando l&#8217;opzione free, che permette 500 chiamate al giorno e 10 al minuto) per ottenere la nostra API KEY.<\/p>\n<p>A questo punto, mettiamo di voler mostrare, proprio come nella mia <a title=\"Napoli, la mia citt\u00e0, informazioni sulla sua storia e previsioni meteo\" href=\"https:\/\/www.flapane.com\/citta.php\" target=\"_blank\">pagina dedicata alla citt\u00e0 di Napoli<\/a>, <strong>la temperatura di due stazioni meteo, farne la media, e mostrare quanto tempo \u00e8 passato dall&#8217;ultimo aggiornamento<\/strong>. <strong>Inoltre, mostrare le previsioni per il giorno e la notte.<\/strong><\/p>\n<p>Qualcosa del tipo:<\/p>\n<p><a href=\"https:\/\/www.flapane.com\/blog\/wp-content\/uploads\/2013\/02\/wunderground-widget.png\" rel=\"lightbox[1316]\"><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-large wp-image-1668 image\" src=\"https:\/\/www.flapane.com\/blog\/wp-content\/uploads\/2013\/02\/wunderground-widget-700x223.png\" alt=\"wunderground widget\" width=\"700\" height=\"223\" srcset=\"https:\/\/www.flapane.com\/blog\/wp-content\/uploads\/2013\/02\/wunderground-widget-700x223.png 700w, https:\/\/www.flapane.com\/blog\/wp-content\/uploads\/2013\/02\/wunderground-widget.png 1223w\" sizes=\"(max-width: 700px) 100vw, 700px\" \/><\/a><\/p>\n<p>Copiamo questo script in una pagina:<\/p>\n<span class=\"no_translate\">\n<pre class=\"brush:php\">&lt;?\r\n\/\/The script shows the latest temperature value from various selected personal Wunderground stations. Also, if desired, it shows today's forecast for the selected city. If you want to use Fahrenheit degrees, please change every occurrence of 'temp_c' to 'temp_f' in the code. Be careful to avoid excessive API calls: you have about 120 calls per day before breaking Wunderground Terms!\r\n\/\/Script by flapane.com - Latest rev. 30-Dec-14\r\n$expiretime=30;\u00a0\u00a0 \u00a0 \/\/cache expire time in minutes\r\n$apikey=\"YOUR_API_KEY\"; \/\/your wunderground api key - 500 calls per day maximum!\r\n$cachename=\"\/home\/yourusername\/domains\/yourwebsite.com\/public_html\/wunder_temp.txt\"; \/\/name of the cachefile\r\n$forecastlang=\"IT\"; \/\/select forecasts language using uppercase letters\r\n$forecastcity=\"Italy\/Naples\"; \/\/in form of State\/City in english. Leave it EMPTY if you don't want any forecasts\r\n$number_stations=\"2\"; \/\/total number of PWS stations.\r\n$station[0]=\"INAPLESN1\"; \/\/wunderground station name (just click on one of the personal weather stations and it will show you their name, ie. KNYBROOK40 for Williamsburg, NYC)\r\n$station[1]=\"INAPOLIP2\";\r\n\/\/Add another station using: $station[2]=\"wunderground station name\";\r\n\r\n\/\/do not mess with the next lines!!!\r\nif (!file_exists($cachename)) {\u00a0\u00a0 \u00a0\/\/create the cachefile if it doesn't exist\r\n\u00a0\u00a0\u00a0\u00a0 $create = fopen($cachename, 'w');\r\n\u00a0\u00a0\u00a0 \u00a0 chmod (\"$cachename\", 0644); \/\/set chmod 644\r\n\u00a0\u00a0 \u00a0 fclose($create);\r\n}\r\n\r\n\/\/ Is the file older than $expiretime, or is the file new\/empty?\r\n$FileAge = time() - filemtime($cachename);\u00a0\u00a0 \u00a0\/\/ Calculate file age in seconds\r\nif ($FileAge &gt; ($expiretime * 60) || 0 == filesize($cachename))\r\n{\r\n\u00a0\u00a0 \u00a0$handle = fopen($cachename, 'wb');\u00a0\u00a0 \u00a0\/\/ Now refresh the cachefile with newer content\u00a0\u00a0 \u00a0\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0for($i=0; $i&lt;$number_stations; $i++){\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0$parsed_json[$i] = json_decode(file_get_contents(\"http:\/\/api.wunderground.com\/api\/{$apikey}\/conditions\/q\/pws:{$station[$i]}.json\"));\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0$pws_freshness = (($parsed_json[$i]-&gt;{'current_observation'}-&gt;{'local_epoch'})-($parsed_json[$i]-&gt;{'current_observation'}-&gt;{'observation_epoch'})); \/\/elapsed time since PWS sent updated data\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0$pws_freshness_human_time = round($pws_freshness\/3600, 0).\" hour(s)\";\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0if (preg_replace(\"\/[^0-9,.]\/\", \"\", $pws_freshness_human_time) &gt; 24) \r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0{\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0$pws_freshness_human_time = round($pws_freshness\/86400, 1).\" day(s)\";\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0}\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0if ($pws_freshness &lt; 3600) \/\/the PWS has been sending fresh data in the last hour\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0{\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0$temp_c[$i] = $parsed_json[$i]-&gt;{'current_observation'}-&gt;{'temp_c'}.\"\\n\";\u00a0\u00a0 \u00a0\/\/add a new line \\n (a capo) to every value\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0}\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0else\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0{\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0$temp_c[$i] = \"&lt;span style='font-weight:normal; font-style: italic;'&gt;(station not reporting in the last $pws_freshness_human_time)&lt;\/span&gt; \".$parsed_json[$i]-&gt;{'current_observation'}-&gt;{'temp_c'}.\"\\n\";\u00a0\u00a0 \u00a0\/\/add a new line \\n (a capo) to every value\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0}\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0$location_wunder[$i] = $parsed_json[$i]-&gt;{'current_observation'}-&gt;{'observation_location'}-&gt;{'city'}.\"\\n\";\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0fwrite($handle,$temp_c[$i]);\u00a0\u00a0 \u00a0\/\/write temps\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0fwrite($handle,$location_wunder[$i]);\u00a0\u00a0 \u00a0\/\/write locations\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0}\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0if(!empty ($forecastcity)){\u00a0\u00a0 \u00a0\/\/do you want to show the forecast for today?\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0$parsed_json_forecast = json_decode(file_get_contents(\"http:\/\/api.wunderground.com\/api\/{$apikey}\/forecast\/lang:{$forecastlang}\/q\/{$forecastcity}.json\"));\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0for($j=0; $j&lt;2; $j++) {\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0$icon_url[$j] = $parsed_json_forecast-&gt;forecast-&gt;txt_forecast-&gt;forecastday[$j]-&gt;icon_url.\"\\n\";\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0$part_of_day[$j] = $parsed_json_forecast-&gt;forecast-&gt;txt_forecast-&gt;forecastday[$j]-&gt;title.\": \".$parsed_json_forecast-&gt;forecast-&gt;txt_forecast-&gt;forecastday[$j]-&gt;fcttext_metric.\"\\n\";\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0fwrite($handle,$icon_url[$j]);\u00a0\u00a0 \u00a0\/\/write url of the daily forecast\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0fwrite($handle,$part_of_day[$j]);\u00a0\u00a0 \u00a0\/\/write the forecasts for both parts of the day\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0}\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0}\r\n}\r\n\r\n\/\/ seconds to minutes - from http:\/\/forums.digitalpoint.com\r\n$minutes = floor($FileAge\/60).\"m\";\r\n$secondsleft = $FileAge%60;\r\n$ago = \"ago\";\r\nif($secondsleft&lt;10)\r\n\u00a0\u00a0\u00a0 $secondsleft = \"0\" . $secondsleft .\"s\";\r\nif($secondsleft&gt;10)\r\n\u00a0\u00a0\u00a0 $secondsleft = $secondsleft .\"s\";\r\nif($minutes&gt;$expiretime){\u00a0\u00a0 \u00a0\/\/avoid weird $FileAge values if cachefile has just been refreshed\r\n\u00a0\u00a0\u00a0 $minutes = \"now\";\r\n\u00a0\u00a0 \u00a0$secondsleft = \"\";\r\n\u00a0\u00a0 \u00a0$ago = \"\";\r\n\u00a0\u00a0 \u00a0}\r\n\u00a0\u00a0 \u00a0\r\n\/\/ Display most recent temperatures and their average value\r\n$display = file($cachename, FILE_IGNORE_NEW_LINES); \/\/ignore \\n for non-reporting stations\r\nforeach ($display as $key=&gt;$value){\r\n\u00a0\u00a0\u00a0 if($key % 2 == 0){ \u00a0\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 $temperature[] = $value; \/\/ EVEN (righe del file cache pari)\r\n\u00a0\u00a0\u00a0 }else{\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 $location_wunder[] = $value;\u00a0 \/\/ ODD\r\n\u00a0\u00a0\u00a0 }\r\n}\r\n\r\nfor($i=0; $i&lt;$number_stations; $i++){\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 $temperature_stripped[$i] = preg_replace(\"\/[^0-9,.-]\/\", \"\", $temperature[$i]);\r\n\u00a0\u00a0 \u00a0}\u00a0\u00a0 \u00a0\r\n\r\n$temp_avg = (array_sum($temperature_stripped)\/$number_stations); \/\/average temperature\r\nfor($i=0; $i&lt;$number_stations; $i++){\r\n\u00a0\u00a0 \u00a0if($temperature[$i] == null){ \/\/if weather station is not reporting data\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 $temperature[$i] = \"N\/A\";\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 $temp_avg = \"N\/A\";\r\n\u00a0\u00a0 \u00a0}\u00a0\u00a0 \u00a0\r\necho \"&lt;b&gt;\".$temperature[$i].\"&lt;\/b&gt;\u00b0C (\".$location_wunder[$i].\") | \";\u00a0\u00a0 \u00a0\r\n}\r\necho \"&lt;b&gt;\".$temp_avg.\"&lt;\/b&gt;\u00b0C (media) | updated $minutes$secondsleft $ago&lt;br \/&gt;&lt;br \/&gt;\";\r\n\r\n\/\/ Display the forecasts ONLY if $forecastcity is not empty\r\nif(!empty ($forecastcity)){\u00a0\u00a0 \u00a0\/\/do you want to show the forecast for today?\r\n$lines = array_slice($display, -4);\r\necho \"&lt;p&gt;&lt;b&gt;Previsioni per oggi:&lt;\/b&gt;&lt;br \/&gt;&lt;img src='$lines[0]' width='50' height='50' border='0' \/&gt; $lines[1]&lt;\/p&gt;\";\r\necho \"&lt;p&gt;&lt;img src='$lines[2]' width='50' height='50' border='0' \/&gt; $lines[3]&lt;\/p&gt;\";\r\n}\r\n\r\necho \"&lt;img src='\/img\/wundergroundlogo.png' \/&gt;\";\u00a0\u00a0 \u00a0\/\/showing WU logo is compulsory\r\n?&gt;<\/pre>\n<p><span class=\"no_translate\"><\/span>Sostituiamo a YOUR_API_KEY la nostra API KEY ottenuta registrandosi a Wunderground, e seguiamo le istruzioni per modificare gli altri valori (es. il corretto formato <em>City\/State<\/em> per le previsioni) di configurazione a nostro piacimento.<\/p>\n<p>Le API ci forniranno una risposta in formato json.<\/p>\n<p>Visto il limite di chiamate giornaliere, e per evitare di appesantire troppo il sito, lo sciprt creer\u00e0 un file di cache chiamato wunder_temp.txt, che si aggiorner\u00e0 ogni $expiretime minuti.<\/p>\n<p>Personalmente credo che 30 minuti fra un aggiornamento e l&#8217;altro, siano pi\u00f9 che sufficienti.<\/p>\n<p>Per trovare le stazioni meteo da inserire al posto di $station[0] e $station[1], dobbiamo selezionare una citt\u00e0 in Wunderground, e cliccare su una qualsiasi stazione fra quelle presenti in <strong>STAZIONI METEO<\/strong>, a fine pagina.<br \/>\nNella pagina che si aprir\u00e0, troveremo il codice della stazione proprio nel titolo, vicino a &#8220;<strong>Storico per: <em>NOMESTAZIONE<\/em><\/strong>&#8220;.<\/p>\n<p>Se non volete mostrare anche le previsioni meteo, \u00e8 sufficiente lasciare VUOTO il campo $forecastcity.<\/p>\n<p>Ricordo che, per usare le API di Weather Underground, \u00e8 necessario mostrar,e vicino ai dati, uno dei loro loghi ufficiali, disponibili a <a href=\"http:\/\/www.wunderground.com\/weather\/api\/d\/docs?d=resources\/logo-usage-guide\" target=\"_blank\">questo indirizzo<\/a>.<\/p>\n<p>Avete utilizzato questo script, o lo avete modificato per recuperare informazioni che non fossero la temperatura ma, per esempio, la pressione atmosferica? Lasciate pure un commento!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Weather Underground \u00e8 un utilissimo sito di meteorologia, che consulto da una decina di anni, che rileva in tempo reale le condizioni atmosferiche e ne trae delle previsioni.<br \/>\nMettiamo di voler mostrare, proprio come nel footer di questo sito, la temperatura di due stazioni meteo, farne la media, e mostrare quanto tempo \u00e8 passato dall&#8217;ultimo aggiornamento.[&#8230;]<\/p>\n","protected":false},"author":1,"featured_media":1317,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[7],"tags":[212,200,24,199,14,15],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.flapane.com\/blog\/wp-json\/wp\/v2\/posts\/1316"}],"collection":[{"href":"https:\/\/www.flapane.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.flapane.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.flapane.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.flapane.com\/blog\/wp-json\/wp\/v2\/comments?post=1316"}],"version-history":[{"count":0,"href":"https:\/\/www.flapane.com\/blog\/wp-json\/wp\/v2\/posts\/1316\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.flapane.com\/blog\/wp-json\/wp\/v2\/media\/1317"}],"wp:attachment":[{"href":"https:\/\/www.flapane.com\/blog\/wp-json\/wp\/v2\/media?parent=1316"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.flapane.com\/blog\/wp-json\/wp\/v2\/categories?post=1316"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.flapane.com\/blog\/wp-json\/wp\/v2\/tags?post=1316"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}