PHP code example of meteoflow / php

1. Go to this page and download the library: Download meteoflow/php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

meteoflow / php example snippets




// 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";

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

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

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

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);

use MeteoFlow\Options\AirQualityOptions;

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

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

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

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 = $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 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
}

$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
}

$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
}

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

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

// 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
}

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";
}

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());
bash
composer