Showcase Example

Today 2PM Weather icon for partially cloudy night 22 °C 5 ms
Today 3PM Weather icon for night rain 22 °C 5 ms
Today 4PM Weather icon for clear day 21 °C 5 ms
Today 5PM Weather icon for partially cloudy day 20 °C 5 ms
Today 6PM Weather icon for rain thunder 18 °C 5 ms
Today 7PM Weather icon for day rain 18 °C 5 ms
Today 8PM Weather icon for daytime thunder 14 °C 5 ms
Today 9PM Weather icon for clear night 16 °C 5 ms
Today 10PM Weather icon for partially cloudy night 15 °C 5 ms
Today 11PM Weather icon for night rain 14 °C 5 ms

DarkSky API for PHP

This is a simple to use DarkSky API for PHP with a SQLite database for caching results for one hour (default). The cache uses latitude, longitude and options as primary key, changing options for the same latitude and longitude pair will therefore result in a fetch operation from DarkSky.

Options for language

ar: Arabic
az: Azerbaijani
be: Belarusian
bg: Bulgarian
bs: Bosnian
ca: Catalan
cs: Czech
de: German
el: Greek
en: English (which is the default)
es: Spanish
et: Estonian
fr: French
hr: Croatian
hu: Hungarian
id: Indonesian
it: Italian
is: Icelandic
kw: Cornish
nb: Norwegian Bokmål
nl: Dutch
pl: Polish
pt: Portuguese
ru: Russian
sk: Slovak
sl: Slovenian
sr: Serbian
sv: Swedish
tet: Tetum
tr: Turkish
uk: Ukrainian
x-pig-latin: Igpay Atinlay
zh: simplified Chinese
zh-tw: traditional Chinese

Options for units

auto: automatically select units based on geographic location
uk2: same as si, except that nearestStormDistance and visibility are in miles and windSpeed is in miles per hour
ca: same as si, except that windSpeed is in kilometers per hour
us: Imperial units (the default)
si: SI units

Read the DarkSky FAQ for more information.

Download DarkSky API

USAGE

<?php
	require_once('dovora.forecast.php');
	use DWeather\DWeather;

	$forecast = new DWeather('YOUR-API-KEY');

	//RETURNS EVERYTHING FOR LATITUDE, LONGITUDE DEFAULT OPTIONS
	var_dump($forecast->get('59','15'));

	//LATITUDE, LONGITUDE WITH OPTIONS [SWEDISH, SI UNITS & EXCLUDES FLAGS]
	//VAR_DUMP EVERY HOUR OF DATA
	foreach ($forecast->get('59','15', array('lang' => 'sv', 'units' => 'si', 'exclude' => 'flags'))->hourly->data as $hour) {
		var_dump($hour);
	}
?>

API

<?php
	namespace DWeather;

	class CacheDatabase extends \SQLite3 {
		function __construct() {
			$this->open('forecast_cache.sqlite');
			$this->query('CREATE TABLE IF NOT EXISTS weather_cache(latitude INTEGER NOT NULL, 
			longitude INTEGER NOT NULL, options TEXT NOT NULL, data TEXT NOT NULL, timestamp 
			DATETIME DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (latitude, longitude, options));');
		}
	}

	class DWeather {	
		const API_ENDPOINT = 'https://api.darksky.net/forecast/';
		const VERBOSE = true;

		private $cache_db;
		private $api_key;
		private $time_start;

		public function __construct($api_key) {
			$this->api_key = $api_key;
			$this->cache_db = new CacheDatabase();
		}

		private function request($latitude, $longitude, $options = array()) {
			$request_url = self::API_ENDPOINT . $this->api_key . '/' . $latitude . ',' . $longitude;

			if (!empty($options)) { $request_url .=  '?' . http_build_query($options); }

			$response = $this->fetchResponse($request_url);
			
			$data = json_encode($response, JSON_UNESCAPED_UNICODE);
			$options = md5(json_encode($options));
			$this->cache_db->query("INSERT OR REPLACE INTO weather_cache(latitude, longitude, options, data) 
			VALUES('{$latitude}','{$longitude}','{$options}','{$data}');");

			return $response;
		}

		private function fetchResponse($url) {
			$ch =  curl_init($url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
			curl_setopt($ch, CURLOPT_TIMEOUT, 3);
			curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));

			return json_decode(curl_exec($ch));
		}

		public function get($latitude, $longitude, $options = array()) {
			$this->time_start = microtime(true);

			$result = null;

			$sqlOptions = md5(json_encode($options));
			$results = $this->cache_db->query("SELECT data FROM weather_cache WHERE latitude = '{$latitude}' AND 
			longitude = '{$longitude}' AND options = '{$sqlOptions}' AND timestamp >= datetime('now', '-1 hours') LIMIT 1");

			if($row = $results->fetchArray()) {
				$this->printVerbose("Result from local cache");
				$result = json_decode($row['data']);
			} else {
				$this->printVerbose("Result from DarkSky");
				$result = $this->request($latitude, $longitude, $options);
			}
			
			$this->printVerbose("Wallclock execution time: " . (microtime(true) - $this->time_start));
			
			return $result;

		}

		private function printVerbose($value) {
			if(self::VERBOSE) {
				echo '<p>'.$value.'<p>';
			}
		}
	}
?>
Download DarkSky API
Golf i Sverige logga
Dovora Interactive Social

Dovora Interactive @ Facebook Dovora Interactive @ Twitter Dovora Interactive @ GooglePlus
Related Pages

Scrolla Till Toppen