PHP SDK for MeteoFlow Weather API

Maintainers

Package info

github.com/MeteoFlow/php

Homepage

pkg:composer/meteoflow/php

Statistics

Installs: 29

Dependents: 1

Suggesters: 0

Stars: 0

Open Issues: 0

1.3.0 2026-02-21 15:20 UTC

This package is not auto-updated.

Last update: 2026-03-07 17:32:01 UTC


README

Official PHP SDK for the MeteoFlow Weather API.

Requirements

  • PHP 5.6 or higher
  • ext-curl
  • ext-json

Installation

Install via Composer:

composer require meteoflow/php

Quick Start

<?php

// Create client
$config = new ClientConfig('YOUR_API_KEY');
$client = new WeatherClient($config);

// Get current weather by location slug
$location = Location::fromSlug('united-kingdom-london');
$response = $client->current($location);

echo "Temperature: {$response->current->temperature}C\n";
echo "Description: {$response->current->description}\n";

API Methods

Weather

Method Description
current($location) Get current weather
forecastHourly($location, $options) Get hourly forecast
forecast3Hourly($location, $options) Get 3-hourly forecast
forecastDaily($location, $options) Get daily forecast

Air Quality & Geomagnetic

Method Description
airQuality($location, $options) Get air quality by days (max 8)
geomagnetic($location) Get geomagnetic activity by days

Geography

Method Description
countries() List all supported countries
citiesByCountry($countryCode) List cities for a country code
searchCities($query, $limit) Search cities by name

Location

The SDK uses a strict ONEOF pattern for locations. You can specify a location by slug, coordinates, or IP address, but not more than one at a time:

By Slug

$location = Location::fromSlug('united-kingdom-london');

By Coordinates

$location = Location::fromCoords(51.5074, -0.1278);

By IP Address

$location = Location::fromIp('8.8.8.8');

Forecast Options

Use ForecastOptions to customize forecast requests:

use MeteoFlow\Options\ForecastOptions;
use MeteoFlow\Options\Unit;

$options = ForecastOptions::create()
    ->setDays(7)                    // Number of days (>= 1)
    ->setUnit(Unit::METRIC)        // 'metric' or 'imperial'
    ->setLang('en');                // BCP-47 language code

$response = $client->forecastDaily($location, $options);

Default Values

When options are not specified, the SDK uses these defaults:

Option Default
days 7
units metric
lang en

Air Quality Options

Use AirQualityOptions to customize air quality requests:

use MeteoFlow\Options\AirQualityOptions;

$options = AirQualityOptions::create()
    ->setDays(6); // Number of days (1..8)

$response = $client->airQuality($location, $options);

Geomagnetic Options

Geomagnetic endpoint does not support options (no days, units, or lang). Use only location:

$response = $client->geomagnetic($location);

Configuration

use MeteoFlow\ClientConfig;

$config = (new ClientConfig('YOUR_API_KEY'))
    ->withBaseUrl('https://api.meteoflow.com')  // Base URL
    ->withTimeout(10)                            // Request timeout in seconds
    ->withConnectTimeout(5)                      // Connection timeout in seconds
    ->withUserAgent('my-app/1.0')               // Custom User-Agent
    ->withDebug(true);                          // Enable debug mode

Response Objects

CurrentWeatherResponse

$response = $client->current($location);

// Place information
$response->place->name;           // City name
$response->place->country;        // Country name
$response->place->lat;            // Latitude
$response->place->lon;            // Longitude

// Current weather
$response->current->temperature;      // Temperature
$response->current->feelsLike;        // Feels like temperature
$response->current->description;      // Weather description
$response->current->humidity;         // Humidity %
$response->current->pressure;         // Pressure
$response->current->windSpeed;        // Wind speed
$response->current->precipitationType; // Precipitation type (rain, snow, none)
$response->current->precipitationMm;  // Precipitation amount in mm
$response->current->iconCode;         // Weather icon code
$response->current->uvIndex;          // UV index value

// Astronomy
$response->astronomy->sunrise;        // Sunrise time (ISO 8601)
$response->astronomy->sunset;         // Sunset time (ISO 8601)
$response->astronomy->dayLength;      // Day length in minutes
$response->astronomy->moonIllumination; // Moon illumination %

Hourly & 3-Hourly Forecast

// Hourly forecast
$response = $client->forecastHourly($location, $options);

// 3-hourly forecast
$response = $client->forecast3Hourly($location, $options);

// Both have same structure
foreach ($response->forecast as $item) {
    $item->date;              // Forecast time (ISO 8601)
    $item->temperature;       // Temperature
    $item->feelsLike;         // Feels like temperature
    $item->description;       // Weather description
    $item->humidity;          // Humidity %
    $item->pressure;          // Pressure
    $item->visibility;        // Visibility in meters
    $item->windSpeed;         // Wind speed
    $item->windDegree;        // Wind direction in degrees
    $item->windGust;          // Wind gust speed
    $item->precipitationType; // Precipitation type
    $item->precipitationMm;   // Precipitation amount in mm
    $item->cloudinessType;    // Cloudiness type (clear, partly cloudy, cloudy)
    $item->iconCode;          // Weather icon code
    $item->iconUrl;           // Weather icon URL
    $item->uvIndex;           // UV index value
    $item->uvDescription;     // UV description (low, moderate, high, very high, extreme)
}

// Astronomy data
foreach ($response->astronomy as $astro) {
    $astro->date;             // Date
    $astro->sunrise;          // Sunrise time
    $astro->sunset;           // Sunset time
}

Daily Forecast

$response = $client->forecastDaily($location, $options);

foreach ($response->daily as $day) {
    $day->date;               // Forecast date (ISO 8601)
    $day->temperatureMin;     // Min temperature
    $day->temperatureMax;     // Max temperature
    $day->description;        // Weather description
    $day->humidityMin;        // Min humidity %
    $day->humidityMax;        // Max humidity %
    $day->pressureMin;        // Min pressure
    $day->pressureMax;        // Max pressure
    $day->visibilityMin;      // Min visibility
    $day->visibilityMax;      // Max visibility
    $day->windSpeed;          // Wind speed
    $day->windDegree;         // Wind direction
    $day->windGust;           // Wind gust speed
    $day->precipitationType;  // Precipitation type
    $day->precipitationMm;    // Precipitation amount in mm
    $day->cloudinessType;     // Cloudiness type
    $day->iconCode;           // Weather icon code
    $day->iconUrl;            // Weather icon URL
    $day->uvIndex;            // UV index value
    $day->uvDescription;      // UV description
}

AirQualityResponse

$response = $client->airQuality($location, $options);

foreach ($response->items as $item) {
    $item->time;                 // Time (ISO 8601)
    $item->particulateMatter2;   // PM2.5
    $item->particulateMatter10;  // PM10
    $item->carbonMonoxide;       // CO
    $item->sulphurDioxide;       // SO2
    $item->nitrogenDioxide;      // NO2
    $item->ozone;                // O3
    $item->aqi;                  // Air quality index
}

GeomagneticResponse

$response = $client->geomagnetic($location);

foreach ($response->items as $item) {
    $item->time;     // Time (ISO 8601)
    $item->valueMax; // Max value for the day
}

Geography Responses

// List all countries
$response = $client->countries();

foreach ($response->countries as $country) {
    $country->slug;  // e.g. "united-kingdom"
    $country->name;  // e.g. "United Kingdom"
    $country->code;  // ISO 3166-1 alpha-2, e.g. "GB"
}

// Cities by country code
$response = $client->citiesByCountry('DE');

foreach ($response->cities as $city) {
    $city->slug;           // e.g. "germany-berlin"
    $city->name;           // City name
    $city->country;        // Country name
    $city->countryCode;    // Country code
    $city->region;         // Region / state name
    $city->lat;            // Latitude
    $city->lon;            // Longitude
    $city->timezoneOffset; // UTC offset in minutes
}

// Search cities by name (limit is optional)
$response = $client->searchCities('Berlin', 5);

foreach ($response->cities as $city) {
    // Same fields as above
}

Error Handling

The SDK throws typed exceptions for different error scenarios:

use MeteoFlow\Exception\ApiException;
use MeteoFlow\Exception\TransportException;
use MeteoFlow\Exception\SerializationException;
use MeteoFlow\Exception\ValidationException;
use MeteoFlow\Exception\MeteoFlowException;

try {
    $response = $client->current($location);
} catch (ValidationException $e) {
    // Invalid input (e.g., days < 1, invalid coordinates)
    echo "Validation error: {$e->getMessage()}\n";
    echo "Field: {$e->getField()}\n";
} catch (TransportException $e) {
    // Network/cURL errors
    echo "Network error: {$e->getMessage()}\n";
    echo "cURL error code: {$e->getCurlErrorCode()}\n";
} catch (ApiException $e) {
    // HTTP 4xx/5xx errors
    echo "API error: {$e->getMessage()}\n";
    echo "HTTP status: {$e->getStatusCode()}\n";
    echo "Error code: {$e->getErrorCode()}\n";
} catch (SerializationException $e) {
    // JSON decode errors
    echo "JSON error: {$e->getMessage()}\n";
} catch (MeteoFlowException $e) {
    // Base exception for all SDK errors
    echo "Error: {$e->getMessage()}\n";
}

Exception Hierarchy

MeteoFlowException (base)
├── TransportException      # Network/cURL errors
├── ApiException            # HTTP 4xx/5xx responses
├── SerializationException  # JSON decode failures
└── ValidationException     # Invalid input

Custom HTTP Transport

You can implement custom HTTP transport for framework integrations:

use MeteoFlow\Transport\HttpTransportInterface;

class MyCustomTransport implements HttpTransportInterface
{
    public function request($method, $url, array $headers = array())
    {
        // Your implementation
        return array(
            'statusCode' => 200,
            'body' => '...',
            'headers' => array(),
        );
    }
}

$client = new WeatherClient($config, new MyCustomTransport());

Examples

See the examples directory for complete usage examples:

Weather

Geography

Air Quality & Geomagnetic

Testing

Run all tests:

./vendor/bin/phpunit

PHP Version Compatibility

The SDK is designed to work with PHP 5.6 and higher:

  • PHP 5.6+: Full compatibility, no typed properties or union types
  • PHP 7.x: Works without modifications
  • PHP 8.x: Works without modifications, benefits from JIT

Framework Integration

This SDK is designed as a standalone package. For framework-specific integrations:

The SDK provides HttpTransportInterface as an extension point for custom transport implementations.

License

MIT License. See LICENSE for details.