dwamianm / noaa
NOAA 库
Requires
- php: >=5.3.0
This package is not auto-updated.
Last update: 2024-09-28 17:54:41 UTC
README
此库提供了NOAA预报和当前天气服务的PHP客户端。
当前天气数据由NOAA当前天气条件的XML源提供。预报数据由NOAA国家数字预报数据库(NDFD)REST Web服务提供。国家海洋和大气管理局(NOAA)是美国的一个联邦机构,因此他们提供的数据仅适用于美国地区。
要求
- PHP 5.3.0+
- PHP cURL
- PHP SimpleXML
当前天气条件
要找到您的当前天气条件,您首先需要知道当地的NOAA气象观测站ID。您可以在以下位置搜索您的本地站ID: http://www.weather.gov/xml/current_obs/。如果您想对站点的数据做些处理,还有一个站点的XML列表:http://www.weather.gov/xml/current_obs/index.xml。以下是一些获取当前天气条件的示例代码
require_once 'noaa/Forecaster.php';
$config = new \noaa\weather\Configuration();
$myWritableCacheDirectory = dirname(__FILE__) . '/cache';
$config->setCache(new \noaa\weather\cache\FileCache($myWritableCacheDirectory));
$forecaster = new \noaa\Forecaster($config);
$stationId = 'KBAF';
try {
// returns a CurrentWeather object or throws an exception on API error
$current = $forecaster->getCurrentWeather($stationId);
} catch (\Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
echo "Temperature: " . $current->getTemperatureF() . " °F\n";
您可以在example/current.php文件中找到更多示例代码。
预报
需要经度和纬度来检索预报数据。有许多API可以将地址和邮编转换为经纬度,但这些转换超出了本库的范围。API提供的数据是6am-6pm(提供位置的地方当地时间)的24小时汇总数据。提供的降水概率是日间和夜间6小时汇总,分别为6am-6pm和6pm-6am。以下是一些获取从当前时间开始7天预报的示例代码
require_once 'noaa/Forecaster.php';
$config = new \noaa\weather\Configuration();
$myWritableCacheDirectory = dirname(__FILE__) . '/cache';
$config->setCache(new \noaa\weather\cache\FileCache($myWritableCacheDirectory));
$forecaster = new \noaa\Forecaster($config);
$lat = '42.16';
$lng = '-72.72';
$startTime = date('Y-m-d', time());
$numDays = 7;
try {
// returns a Forecast object or throws an exception on API error
$forecast = $forecaster->getForecastByLatLng($lat, $lng, $startTime, $numDays);
} catch (\Exception $e) {
echo "There was an error fetching the forecast: " . $e->getMessage() . "\n";
}
// get ForecastDay object for the first day of the forecast
$day = $forecast->getDay(0);
echo "High Temperature: " . $day->getHighTemperature() . "\n";
您可以在example/forecast.php文件中找到更多示例代码。
夜间预报
对于晚上6点后制作的预报(当地时间),预报结果中的第一天将是“明天”。doesStartAtNight()方法会告诉您预报是否是“夜间”预报
$forecast->doesStartAtNight();
还有一个信息项对“今天”仍然有价值,那就是从晚上6点到早上6点的降水概率。可以通过这种方式检索该概率
if ($forecast->doesStartAtNight()) {
$tonightsPrecipitation = $forecast->getPrecipitationProbabilityTonight();
}
缓存
NOAA建议API消费者每小时只请求一次新数据。此库提供了一个简单易用的FileCache类,只需在存储缓存数据的可写目录即可。它将根据文件修改时间自行处理缓存失效。您设置的目录必须存在且可写。
如果您想使用除了提供的FileCache之外的缓存,创建自己的缓存也很简单。只需创建一个实现\ noaa\weather\cache\Cache接口的类。使用setCache()配置方法设置您自己的自定义缓存类。请参阅noaa/weather/cache/ArrayCache.php文件以获取示例。
要实例化一个没有缓存机制的Forecaster对象(不推荐!)
require_once 'noaa/Forecaster.php';
$forecaster = new \noaa\Forecaster();