Skip to content

Commit 2add629

Browse files
committed
Added error handling and documentation, closes #1.
1 parent 4fa83b9 commit 2add629

File tree

4 files changed

+146
-2
lines changed

4 files changed

+146
-2
lines changed

Examples.php

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
* @see http://www.OpenWeatherMap.org
1212
* @see http://www.OpenWeatherMap.org/about
1313
* @see http://www.OpenWeatherMap.org/copyright
14+
* @see http://openweathermap.org/appid
1415
*/
1516

1617
// Include api class
@@ -188,7 +189,37 @@
188189
echo OpenWeatherMap::getRawData('Berlin', $units, $lang, null, 'html');
189190
echo "<br />\n";
190191

191-
// Example 14: Using an api key:
192+
// Example 14: Error handling.
193+
echo "<br /><br />\n\n\nEXAMPLE 14<hr />\n\n\n";
194+
195+
// Try wrong city name.
196+
try {
197+
$weather = OpenWeatherMap::getWeather("ThisCityNameIsNotValidAndDoesNotExist", $units, $lang);
198+
} catch(OpenWeatherMap_Exception $e) {
199+
echo $e->getMessage() . ' (Code ' . $e->getCode() . ').';
200+
echo "<br />\n";
201+
}
202+
203+
// Try invalid $query.
204+
try {
205+
$weather = OpenWeatherMap::getWeather(new DateTime('now'), $units, $lang);
206+
} catch(Exception $e) {
207+
echo $e->getMessage() . ' (Code ' . $e->getCode() . ').';
208+
echo "<br />\n";
209+
}
210+
211+
// Full error handling would look like this:
212+
try {
213+
$weather = OpenWeatherMap::getWeather(-1, $units, $lang);
214+
} catch(OpenWeatherMap_Exception $e) {
215+
echo 'OpenWeatherMap exception: ' . $e->getMessage() . ' (Code ' . $e->getCode() . ').';
216+
echo "<br />\n";
217+
} catch(Exception $e) {
218+
echo 'General exception: ' . $e->getMessage() . ' (Code ' . $e->getCode() . ').';
219+
echo "<br />\n";
220+
}
221+
222+
// Example 15: Using an api key:
192223

193224
# OpenWeatherMap::getWeather('Berlin', $units, $lang, 'Your-Api-Key-Here');
194225
# OpenWeatherMap::getRawData('Berlin', $units, $lang, 'Your-Api-Key-Here', 'json');

OpenWeatherMap.php

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,58 @@
1111
* @see http://www.OpenWeatherMap.org
1212
* @see http://www.OpenWeatherMap.org/about
1313
* @see http://www.OpenWeatherMap.org/copyright
14+
* @see http://openweathermap.org/appid
1415
*/
1516

1617
require_once('Util.php');
1718

19+
/**
20+
* Main static class for the OpenWeatherMap-PHP-API.
21+
*/
1822
class OpenWeatherMap
1923
{
24+
/**
25+
* @const $url The basic api url to fetch data from.
26+
*/
2027
const url = "http://api.openweathermap.org/data/2.5/weather?";
2128

29+
/**
30+
* Directly returns the xml/json/html string returned by OpenWeatherMap.
31+
*
32+
* @param array|int|string $query The place to get weather information for. For possible values see below.
33+
* @param string $units Can be either 'metric' or 'imperial' (default). This affects almost all units returned.
34+
* @param string $lang The language to use for descriptions, default is 'en'. For possible values see below.
35+
* @param string $appid Your app id, default ''. See http://openweathermap.org/appid for more details.
36+
* @param string $mode The format of the data fetched. Possible values are 'json', 'html' and 'xml' (default).
37+
*
38+
* @return bool|string Returns false on failure and the fetched data in the format you specified on success.
39+
*
40+
* @warning If an error occured, OpenWeatherMap returns data in json format ALWAYS
41+
*
42+
* There are three ways to specify the place to get weather information for:
43+
* - Use the city name: $query must be a string containing the city name.
44+
* - Use the city id: $query must be an integer containing the city id.
45+
* - Use the coordinates: $query must be an associative array containing the 'lat' and 'lon' values.
46+
*
47+
* Available languages are (as of 17. July 2013):
48+
* - English - en
49+
* - Russian - ru
50+
* - Italian - it
51+
* - Spanish - sp
52+
* - Ukrainian - ua
53+
* - German - de
54+
* - Portuguese - pt
55+
* - Romanian - ro
56+
* - Polish - pl
57+
* - Finnish - fi
58+
* - Dutch - nl
59+
* - French - fr
60+
* - Bulgarian - bg
61+
* - Swedish - se
62+
* - Chinese Traditional - zh_tw
63+
* - Chinese Simplified - zh_cn
64+
* - Turkish - tr
65+
*/
2266
static public function getRawData($query, $units = 'imperial', $lang = 'en', $appid = '', $mode = 'xml')
2367
{
2468
switch($query) {
@@ -45,6 +89,43 @@ static public function getRawData($query, $units = 'imperial', $lang = 'en', $ap
4589
return file_get_contents($url);
4690
}
4791

92+
/**
93+
* Returns the current weather at the place you specified as an object.
94+
*
95+
* @param array|int|string $query The place to get weather information for. For possible values see below.
96+
* @param string $units Can be either 'metric' or 'imperial' (default). This affects almost all units returned.
97+
* @param string $lang The language to use for descriptions, default is 'en'. For possible values see below.
98+
* @param string $appid Your app id, default ''. See http://openweathermap.org/appid for more details.
99+
*
100+
* @throws Exception If $query has a wrong format. For valid formats see below.
101+
* @throws OpenWeatherMap_Exception If OpenWeatherMap returns an error.
102+
*
103+
* @return object Returns a new Weather object.
104+
*
105+
* There are three ways to specify the place to get weather information for:
106+
* - Use the city name: $query must be a string containing the city name.
107+
* - Use the city id: $query must be an integer containing the city id.
108+
* - Use the coordinates: $query must be an associative array containing the 'lat' and 'lon' values.
109+
*
110+
* Available languages are (as of 17. July 2013):
111+
* - English - en
112+
* - Russian - ru
113+
* - Italian - it
114+
* - Spanish - sp
115+
* - Ukrainian - ua
116+
* - German - de
117+
* - Portuguese - pt
118+
* - Romanian - ro
119+
* - Polish - pl
120+
* - Finnish - fi
121+
* - Dutch - nl
122+
* - French - fr
123+
* - Bulgarian - bg
124+
* - Swedish - se
125+
* - Chinese Traditional - zh_tw
126+
* - Chinese Simplified - zh_cn
127+
* - Turkish - tr
128+
*/
48129
static public function getWeather($query, $units = 'imperial', $lang = 'en', $appid = '')
49130
{
50131
return new Weather($query, $units, $lang, $appid);

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ An php api to parse weather data from [OpenWeatherMap.org](http://www.OpenWeathe
44

55
If you are looking for an implementation for the [CMS Zikula](http://www.zikula.org), you may want to take a look at [cmfcmf/Weather](https://github.com/cmfcmf/Weather).
66

7+
For example code and how to use this api, please take a look into `Examples.php` or run it in your browser.
8+
79
**Notice:** This api is not made by OpenWeatherMap, nor their offical php api.
810

911
License

Util.php

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
* @see http://www.OpenWeatherMap.org
1212
* @see http://www.OpenWeatherMap.org/about
1313
* @see http://www.OpenWeatherMap.org/copyright
14+
* @see http://openweathermap.org/appid
1415
*/
1516

1617
/**
@@ -46,7 +47,31 @@ class Weather
4647

4748
public function __construct($query, $units = 'imperial', $lang = 'en', $appid = '')
4849
{
49-
$xml = new SimpleXMLElement(OpenWeatherMap::getRawData($query, $units, $lang, $appid, 'xml'));
50+
// Disable default error handling of SimpleXML (Do not throw E_WARNINGs).
51+
libxml_use_internal_errors(true);
52+
libxml_clear_errors();
53+
54+
$answer = OpenWeatherMap::getRawData($query, $units, $lang, $appid, 'xml');
55+
if ($answer === false) {
56+
// $query has the wrong format, throw error.
57+
throw new Exception('Error: $query has the wrong format. See the documentation of OpenWeatherMap::getRawData() to read about valid formats.');
58+
}
59+
60+
try {
61+
$xml = new SimpleXMLElement($answer);
62+
} catch(Exception $e) {
63+
// Invalid xml format. This happens in case OpenWeatherMap returns an error.
64+
// OpenWeatherMap always uses json for errors, even if one specifies xml as format.
65+
$error = json_decode($answer, true);
66+
if (isset($error['message'])) {
67+
throw new OpenWeatherMap_Exception($error['message'], $error['cod']);
68+
} else {
69+
throw new OpenWeatherMap_Exception('Unknown fatal error: OpenWeatherMap returned the following json object: ' . print_r($error));
70+
}
71+
}
72+
// Check for errors.
73+
$errors = libxml_get_errors();
74+
print_r($errors);
5075

5176
$this->city = new _City($xml->city['id'], $xml->city['name'], $xml->city->coord['lon'], $xml->city->coord['lat'], $xml->city->country);
5277
$this->temperature = new _Temperature(new _Unit($xml->temperature['value'], $xml->temperature['unit']), new _Unit($xml->temperature['min'], $xml->temperature['unit']), new _Unit($xml->temperature['max'], $xml->temperature['unit']));
@@ -242,3 +267,8 @@ public function getIconUrl()
242267
return str_replace("%s", $this->icon, $this->iconUrl);
243268
}
244269
}
270+
271+
class OpenWeatherMap_Exception extends Exception
272+
{
273+
274+
}

0 commit comments

Comments
 (0)