Last active
August 17, 2018 13:37
-
-
Save chak10/d80da318ba46bca1a7163311da5a16ec to your computer and use it in GitHub Desktop.
Current condition
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class OpenWeatherMap | |
{ | |
var $api; | |
/** | |
* OpenWeatherMap constructor. | |
* @param $a | |
*/ | |
function __construct($a) | |
{ | |
$this->api = $a; | |
} | |
/** | |
* @param $a | |
* @param $u | |
* @param $l | |
* @return bool|mixed | |
*/ | |
public function getWeather($a, $u = "metric", $l = "en") | |
{ | |
$api = $this->api; | |
$id = $q = $lat = $lon = $zip = $city = false; | |
if (is_string($a)) | |
$q = $a; | |
if (is_array($a)) { | |
if (isset($a["lat"]) && isset($a["lon"])) { | |
$lat = $a["lat"]; | |
$lon = $a["lon"]; | |
} | |
if (isset($a['q'])) | |
$q = $a['q']; | |
if (isset($a['id'])) | |
$id = $a['id']; | |
if (isset($a['zip']) && isset($a['city'])) { | |
$zip = $a['zip']; | |
$city = $a['city']; | |
} | |
} | |
if ($id) { | |
$url = "https://api.openweathermap.org/data/2.5/weather?id=$id&appid=$api&units=$u&lang=$l"; | |
if ($r = $this->get($url)) | |
return json_decode($r); | |
return false; | |
} | |
if ($q) { | |
$url = "https://api.openweathermap.org/data/2.5/weather?q=$q&appid=$api&units=$u&lang=$l"; | |
if ($r = $this->get($url)) | |
return json_decode($r); | |
return false; | |
} | |
if ($lat && $lon) { | |
$url = "https://api.openweathermap.org/data/2.5/weather?lat=$lat&lon=$lon&appid=$api&units=$u&lang=$l"; | |
if ($r = $this->get($url)) | |
return json_decode($r); | |
return false; | |
} | |
if ($zip && $city) { | |
$url = "https://api.openweathermap.org/data/2.5/weather?zip=$zip,$city&appid=$api&units=$u&lang=$l"; | |
if ($r = $this->get($url)) | |
return json_decode($r); | |
return false; | |
} | |
return false; | |
} | |
/** | |
* Send a GET requst using cURL | |
* @param string $url to request | |
* @param array $get values to send | |
* @param array $options for cURL | |
* @return string | |
*/ | |
private function get($url, array $options = array()) | |
{ | |
$defaults = array( | |
CURLOPT_URL => $url, | |
CURLOPT_HEADER => 0, | |
CURLOPT_RETURNTRANSFER => true, | |
CURLOPT_TIMEOUT => 4 | |
); | |
$ch = curl_init(); | |
curl_setopt_array($ch, ($options + $defaults)); | |
if (!$result = curl_exec($ch)) | |
trigger_error(curl_error($ch)); | |
curl_close($ch); | |
return $result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment