Aby móc używać funkcji potrzebny jest API key do zdobycia za free na: http://www.wunderground.com/weather/api/
wunderground.com daje też obrazki które można wykorzystać. Nazwy obrazków masz w kluczu icon tablicy dla odpowiedniego dnia. Można je zdobyć tutaj: http://www.wunderground.com/weather/api/d/...urces/icon-sets
UWAGA! powinieneś cache'ować zwrotki tej funkcji a nie za każdym razem od nowa pobierać nowe dane. Po pierwsze ponieważ jest to nie wydajne, a po drugie API ma ograniczenie na 500 zapytań dziennie i 10 na minute. Wystarczy odpytywać się o nową pogodę co 15 minut, a nawet dłużej.
Kod
<?php /** * Get weather forecast information from wunderground.com * * IMPORTANT NOTE: * You should cache output of this function in some kind of cache in order to prevent requesting for forecast data * on every page refresh. wunderground.com has limits that are for now 500 request per day and 10 per minute. * So if you do not cache response you will exceed them quickly. * * @param string $_place Weather for which place? Examples: Poland/Jaslo * ( do not use local chars, only ASCII ) * if needed use some kind of string normalizer * @param string $_apiKey API key to wunderground.com, can be obtained for free using URL: * <a href="http://www.wunderground.com/weather/api/" target="_blank">http://www.wunderground.com/weather/api/</a> * @param bool $_throwException should function throws Exception instead just returning false? * @throws Exception * @return array|boolean array with data or false if request failed */ function weatherFor( $_place, $_apiKey, $_throwException = false ) { $url = "http://api.wunderground.com/api/$_apiKey/forecast/q/$_place.json"; // set request timeout 'timeout' => 2 ) ) ); // request data // check if request succeeded if( $jsonString === false ) { if ( $_throwException ) { throw new Exception('function weatherFor: file_get_contents failed'); } return false; } // decode JSON $weatherInfo = json_decode( $jsonString, true ); // check if response is JSON if( json_last_error() !== JSON_ERROR_NONE ) { if ( $_throwException ) { throw new Exception('function weatherFor: Response not JSON'); } return false; } // check if error in response if ( $_throwException ) { throw new Exception('function weatherFor: Error in response'); } return false; } return $weatherInfo; }
Przykładowy wywołanie:
$weatherForecast = weatherFor( 'Poland/Jaslo', 'place for api key' ); if( $weatherForecast !== false ) { // u can safely use response to generate weather panel or something } else { }
Przykładowa zwrotka funkcji:
http://pastebin.com/pHBF0Zd0