meteosource/meteosource_php

PHP封装库,用于全球天气API - 超本地天气预报

v1.0.1 2022-09-29 11:41 UTC

This package is auto-updated.

Last update: 2024-09-29 06:20:31 UTC


README

PHP封装库,用于Meteosource天气API,为地球上的任何位置提供详细的超本地天气预报。

安装

使用Composer进行安装。

composer require meteosource/meteosource_php

开始使用

要使用此库,您需要获取您的Meteosource API密钥。您可以在这里注册,或在您的仪表板中获取现有账户的API密钥。

库使用

初始化

要初始化Meteosource对象,您需要API密钥和您的订阅计划(层)名称。以下是一个初始化的基本示例

<?php
// Change this to your actual API key
const YOUR_API_KEY = 'abcdefghijklmnopqrstuvwxyz0123456789ABCD';
// Change this to your actual tier
const YOUR_TIER = 'flexi';

// Initialize the main Meteosource object
$meteosource = new Meteosource\Meteosource(YOUR_API_KEY, YOUR_TIER);

获取天气数据

使用meteosource库,您可以获取天气预报或存档天气数据(如果您有付费订阅)。

预报

要获取指定地点的天气数据,请使用Meteosource对象的getPointForecast()方法。您必须指定地点的坐标(lat + lon)或place_id。参数的详细说明可以在API文档中找到。

请注意,默认时区始终是UTC,与API本身(默认为点的本地时区)相反。这是因为库始终查询API以获取UTC时区,以避免模糊的时间日期问题。如果您指定了不同的时区,库仍然请求API以获取UTC,然后将其转换为所需的时区。

<?php
// Get the forecast for given point
$forecast = $meteosource->getPointForecast(
    null,  // You can specify place_id instead of lat+lon
    37.7775,  // Latitude of the point
    -122.416389,  // Longitude of the point
    ['current', 'hourly'],  // Defaults to '("current", "hourly")'
    'US/Pacific',  // Defaults to 'UTC', regardless of the point location
    'en',  // Defaults to 'en'
    'auto'  // Defaults to 'auto'
);

历史天气

拥有Meteosource付费订阅的用户可以使用time_machine端点通过getTimeMachine()方法检索历史天气。

<?php
// Get the historical weather
$timeMachine = $meteosource->getTimeMachine(
    '2019-12-25', // You can also pass array of dates, which can be string or DateTime objects
    null, // Start date - you can specify the range for dates you need, instead of array
    null, // End date  - you can specify the range for dates you need, instead of array
    'london', // ID of the place you want the historical weather for
    null, // You can specify lat instead of place_id
    null, // You can specify lon instead of place_id
    'UTC', // Defaults to 'UTC', regardless of the point location
    'us' // Defaults to 'auto'
);

请注意,历史天气数据始终按完整UTC天检索。如果您指定了不同的时区,日期时间将进行转换,但它们将覆盖完整的UTC,而不是本地日。如果您将datetime指定为任何日期参数,则忽略小时、分钟、秒和微秒。因此,如果您请求'2021-12-25T23:59:59',您将获得完整的UTC天2021-12-25的数据。

如果您将日期的数组传递给date参数,则这些日期将按迭代顺序插入到内部结构中。这会影响整数时间索引(见下文)。对于每个日期都会进行API请求,即使您指定了日期范围。

处理天气数据

所有meteosource的数据对象都具有重载的__toString()方法,因此您可以echo对象以获取有关它们的有用信息

<?php
echo $forecast;  // <Forecast for lat: 37.7775, lon: -122.416389>
echo $timeMachine;  // <TimeMachine for lat: 51.50853, lon: -0.12574>

属性访问

库将JSON响应加载到其内部结构中。您可以使用对象操作符(->)或索引操作符([])访问属性

<?php
// You can access all of the attributes with object operator:
echo $forecast->lat; // 37.7775

// ... or with index operator:
echo $forecast['lon'];  // -122.416389

// There is also information about the elevation of the point and the timezone
echo $timeMachine->elevation;  // 82
echo $timeMachine->timezone;  // 'UTC'

天气数据部分

Forecast对象中有5个天气预报部分(currentminutelyhourlydailyalerts)作为属性。

current数据包含单个时间点(由SingleTimeData对象表示)的多个变量的数据

<?php
// <Instance of SingleTimeData (current) with 17 member variables (cloud_cover,
//  dew_point, feels_like, humidity, icon, icon_num, irradiance, ozone,
//  precipitation, pressure, summary, temperature, uv_index, visibility,
// wind, wind_chill)>
echo $forecast->current;

minutelyhourlydaily部分包含更多时间点的预测(由MultipleTimesData表示)。未请求的部分为空(null)

<?php
echo $forecast->minutely  // null

所需的部分也可以通过echo显示,以查看可用的步进数及其范围(包含)

<?php
// <Hourly data with 164 timesteps
//  from 2021-09-08T22:00:00 to 2021-09-15T17:00:00>
echo $forecast->hourly;

alerts部分包含气象警报和预警,如果该位置发布了任何警报。alerts对象是AlertsData类的实例。您可以打印该对象或遍历它

<?php
echo $forecast->alerts; // <Alerts data containing 4 alerts>
foreach($alerts as $alert) {
    // <Instance of SingleTimeData with 8 member variables
    //  (certainty, description, event, expires, headline, onset, sender, severity)>
    echo $alert;
}

您还可以获取给定时间所有活动警报的列表。如果在这个函数中使用string或tz-naive DateTime,它将假定它与请求的预报在同一时区

<?php
// If you pass no parameter, it checks for current time
$forecast->alerts->getActive(); // returns list of SingleTimeData instances
// You can use either string...
$forecast->alerts->getActive('2022-03-08T22:00:00');
// ... or datetime (both tz-aware and naive)
$forecast->alerts->getActive(new DateTime('2022-03-08T22:00:00'));

TimeMachine对象中,有一个名为data的单个部分作为历史天气的属性,由MultipleTimesData表示。

<?php
echo $timeMachine->data  // <Instance of MultipleTimesData (time_machine) with 24 timesteps from 2019-12-25T00:00:00 to 2019-12-25T23:00:00>

时间索引

如上所述,Forecastminutelyhourlydaily部分以及TimeMachinedata部分包含更多步进的数据。要获取单个时间的数据,您有几种选择。

1. 整数索引

您可以直接用整数索引MultipleTimesData实例,作为从当前时间的偏移量

<?php
$forecast->hourly[0];
$timeMachine->data[0];

2. 字符串索引

要获取确切的时间,您可以使用string,格式为YYYY-MM-DDTHH:00:00。假定datetime字符串与数据处于同一时区。

<?php
// Get a date in near future for which there are data in the current API response
$currentDate = (new DateTime())->add(new DateInterval('PT1H'));
$forecast->hourly[$currentDate];

// Get historical weather
$timeMachine->data['2019-12-25T03:00:00']

3. datetime索引

您还可以使用DateTime作为索引,它将自动转换为数据的时区。

<?php
// Get a date in near future for which there are data in the current API response
$currentDt = new DateTime("Y-m-d\TH:00:00");

// Index with DateTime
$forecast->hourly[$currentDt]->temperature;

// Get historical weather
$timeMachine->data[new DateTime('2019-12-25')];

注意:minutelyhourlydailyalertsArrayIterator类型

变量访问

要访问变量,您可能需要使用对象操作符(->

<?php
$forecast->current->temperature;
$forecast->hourly[0]->temperature;
$timeMachine->data[0]->weather  // cloudy

一些变量被组合成逻辑组,就像在API响应中一样。您可以使用链式对象操作符(->)访问实际数据

<?php
$forecast->current->wind->speed;

测试

单元测试使用PHPUnit编写。您需要通过环境变量提供您的实际API密钥。要运行测试,请使用

# Change this to your actual API key
export METEOSOURCE_API_KEY='abcdefghijklmnopqrstuvwxyz0123456789ABCD'
vendor/bin/phpunit tests

联系我们

您可以通过这里联系我们。