Пример получения информации о погоде на php
Получение информации о погоде через OpenWeatherMap
12.09.2017
Выбран именно OpenWeatherMap, т.к. его API бесплатные в отличии от Яндекс Погода и Гисметео.
class.weather.php (Download)
<?
// OpenWeatherMap
class soWeather
{
const ApiURL = 'http://api.openweathermap.org/data/2.5/';
const ApiKey = 'XXX';
/**
* Возвращает все данные о текущей погоде
*
* https://openweathermap.org/current#current_JSON
*
* @param int $id_city
*
* @return object
*/
protected function _getCurrentWeatherAll($id_city)
{
// imperial metric
$s = file_get_contents(self::ApiURL.'weather?id='.$id_city.'&units=metric&appid='.self::ApiKey);
return json_decode($s);
}
/**
* Возвращает нужные данные о текущей погоде
*
* @param int $id_city
*
* @return object
*/
protected function _getCurrentWeather($id_city)
{
$oRet = new stdClass();
$oTMP = $this->_getCurrentWeatherAll($id_city);
$oRet->temperature = $oTMP->main->temp;
$oRet->pressure = $oTMP->main->pressure * 0.75008;
return $oRet;
}
/**
* Возвращает все данные о прогнозе погоды
*
* http://openweathermap.org/forecast5
*
* @param int $id_city
*
* @return object
*/
protected function _getForecastALL($id_city)
{
// imperial metric
$s = file_get_contents(self::ApiURL.'forecast?id='.$id_city.'&units=metric&appid='.self::ApiKey);
return json_decode($s);
}
/**
* Возвращает нужные данные о прогнозе погоды
*
* @param int $id_city
*
* @return array
*/
protected function _getForecast($id_city)
{
$aRet = array();
$oForecast = $this->_getForecastALL($id_city);
$i = 0;
foreach($oForecast->list as $oRow)
{
$oTMP = new stdClass();
$oTMP->dt = date("H:i:s", $oRow->dt);
$oTMP->temperature = $oRow->main->temp;
$oTMP->pressure = $oRow->main->pressure * 0.75008;
$aRet[] = $oTMP;
if($i > 4)
{
break;
}
$i++;
/*
echo '<pre>';
print_r($oRow);
echo '</pre>';
*/
}
return $aRet;
}
/**
* Возвращает все данные
*
* @return object
*/
public function getWeatherData()
{
//$id = 524901; // Moscow
$id = 523812; // Mytishchi
//$oRet = $this->_getCurrentWeather($id);
$oRet = $this->_getForecast($id);
return $oRet;
}
}index.php (Download)
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
require_once(__DIR__.'/class.weather.php');
$oWeather = new soWeather();
echo '<pre>';
print_r($oWeather->getWeatherData());
echo '</pre>';