Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- //Определение города
- function getGeo($ip){
- if(!filter_var($ip, FILTER_VALIDATE_IP, array('flags' => FILTER_FLAG_IPV4)))
- return FALSE;
- $get = file_get_contents("http://ipgeobase.ru:7020/geo?ip={$ip}");
- $xml = simplexml_load_string($get);
- $city = isset($xml->ip->city) ? strtolower($xml->ip->city) : '';
- return $city;
- }
- class weather{
- private $cache_dir;
- public $city_id;
- private $noon; //Время дня. По-умолчанию 4 - основная часть дня 11:00-20:00
- private $night; //Время ночи. По-умолчанию 5
- //Инициализируем класс
- public function __construct(){
- $this->cache_dir=$_SERVER['DOCUMENT_ROOT'].'/habr/cache/weather/';
- $this->noon=4;
- $this->night=5;
- if(isset($_SESSION['weather_city'])){$cityname=$_SESSION['wether_city'];} //Берем название города из сессии
- else{$cityname=getGeo($_SERVER['REMOTE_ADDR']); }// Получаем название города по автоопределению
- $cities=json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'].'/habr/weather/YandexCities.txt'));
- if(isset($cities->$cityname)){
- $this->city_id=$cities->$cityname;
- } else {
- $this->city_id=$cities->{'Махачкала'};
- }
- }
- //Возвращает плюс, минус или ноль в зависимости от температуры
- public function checkZeroMark($temperature){
- if($temperature>0){
- return '+'.$temperature;
- } elseif ($temperature<0){
- return '-'.$temperature;
- }
- return $temperature;
- }
- //Получаем погоду для определенного города
- public function getCityWeather(){
- $_LANG['MONTHS'] = array(
- 'Jan'=>'январь', 'Feb'=>'февраль', 'Mar'=>'март',
- 'Apr'=>'апрель', 'May'=>'май','Jun'=>'июнь',
- 'Jul'=>'июль','Aug'=>'август', 'Sep'=>'сентябрь',
- 'Oct'=>'октябрь','Nov'=>'ноябрь','Dec'=>'декабрь');
- $_LANG['WEEKDAYS'] = array(
- 'Sunday'=>'воскресенье', 'Monday'=>'понедельник',
- 'Tuesday'=>'вторник', 'Wednesday'=>'среда',
- 'Thursday'=>'четверг', 'Friday'=>'пятница',
- 'Saturday'=>'суббота');
- $city_cache=$this->{cache_dir}.$this->{city_id};
- //Если время последнего изменения кэш файла меньше шести минут, возвращаем данные из кэша
- if(file_exists($city_cache) && filemtime($city_cache)>time()-360){
- $jsoned_weather=json_decode(file_get_contents($city_cache),TRUE);
- } else { //Если кэш отсутствует, получаем данные с яндекса
- $weather=simplexml_load_file('http://export.yandex.ru/weather-ng/forecasts/'.$this->city_id.'.xml');
- if($weather!=null){
- //Погода на семь дней
- for($i=1; $i<=7; $i++)
- {
- if($weather->day[$i]!=null){
- $days['sevendays'][]=array(
- 'weekday' => strtr(date('l', strtotime($weather->day[$i]->attributes()->date)), $_LANG['WEEKDAYS']),
- 'data'=>strtr(date("j M",strtotime($weather->day[$i]->attributes()->date)), $_LANG['MONTHS']),
- 'temp_day' => $this->checkZeroMark($weather->day[$i]->day_part[$this->noon]->temperature),
- 'temp_night' => $this->checkZeroMark($weather->day[$i]->day_part[$this->night]->temperature),
- 'weather_type' => $weather->day[$i]->day_part[$this->noon]->weather_type,
- 'wind_speed' => $weather->day[$i]->day_part[$this->noon]->wind_speed,
- 'humidity' => $weather->day[$i]->day_part[$this->noon]->humidity,
- 'pressure' => $weather->day[$i]->day_part[$this->noon]->pressure,
- 'image' => $weather->day[$i]->day_part[$this->noon]->{'image-v3'}
- );
- }
- }
- //Погода на сегодня
- $days['today']=array(
- 'weekday' => strtr(date('l'), $_LANG['WEEKDAYS']),
- 'data'=>strtr(date('j M Y, G:i'), $_LANG['MONTHS']),
- 'temperature' => $this->checkZeroMark($weather->fact->temperature),
- 'weather_type' => $weather->fact->weather_type,
- 'wind_speed' => $weather->fact->wind_speed,
- 'humidity' => $weather->fact->humidity,
- 'pressure' => $weather->fact->pressure,
- 'water_temp' => $this->checkZeroMark($weather->fact->water_temperature),
- 'sunrise' => $weather->day->sunrise,
- 'sunset' => $weather->day->sunset,
- 'image' => $weather->fact->{'image-v3'},
- 'city'=>$weather->attributes()->city,
- 'country' => $weather->attributes()->country
- );
- file_put_contents($city_cache, json_encode($days));
- $jsoned_weather=json_decode(file_get_contents($city_cache), TRUE);
- } else{
- return null;
- }
- }
- return $jsoned_weather;
- }
- }
- $weather=new weather;
- $jsoned_weather=$weather->getCityWeather();
- $today=$jsoned_weather['today'];
- $sevendays=$jsoned_weather['sevendays'];
- ?>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" >
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
- <title>Погода от Яндекса</title>
- </head>
- <body>
- <style>
- #weather{
- margin-top:-10px;
- background: url('/habr/weather/sun.jpg') no-repeat;
- background-size:cover;
- padding:10px;
- min-height:300px;
- width:790px;
- }
- #weather table{
- width:790px;
- background-color:RGBa(0,0,0,0.4);
- color:white;
- }
- #weather td{
- vertical-align:middle;
- }
- </style>
- <div id="weather">
- <table cellpadding="0" cellspacing="0" border="0">
- <tbody>
- <tr>
- <td style="padding:10px 13px 0;">
- <span style="font-size:24px;"><?php echo $today['city']['0'].', '.$today['country']['0'];?></span>
- </td>
- </tr>
- <tr>
- <td style="padding:0 13px;">
- сегодня <?php echo $today['weekday'].', '.$today['data'];?>
- </td>
- <tr >
- <td>
- <img style="margin-left:20px; width:70px; height:70px;" src="/habr/weather/img/<?php echo $today['image']['0'];?>.png"
- title="<?php echo $today['weather_type']['0']; ?>">
- <span style="font-size:100px; font-family:Arial;"><?php echo $today['temperature'];?>°</span>
- </td>
- <td style="height:70px; width:190px;">
- <?php echo $today['weather_type']['0'];?><br/>
- <?php if($today['water_temp']!=null){
- echo 'температура воды '.$today['water_temp'].'°';
- }
- ?>
- </td>
- <td style="padding-left:5px;">
- <?php
- echo ' Атм. давление '.$today['pressure']['0'].' мм. рт.ст.<br/>
- Влажность '.$today['humidity']['0'].'% <br/>
- Скорость ветра '.$today['wind_speed']['0'].' м/с <br/>
- Рассвет '.$today['sunrise']['0'].' / Закат '.$today['sunset']['0'];
- ?>
- </td>
- </tr>
- </tbody>
- </table>
- <br/>
- <table cellpadding="0" cellspacing="0" border="0">
- <tbody style="text-align:center;">
- <tr>
- <?php
- if($sevendays!=false){
- foreach($sevendays as $day){
- ?>
- <td style="width:100px; vertical-align:top; text-align:left; padding:2px 5px;">
- <a title="<?php echo $day['weekday'].'">'.$day['data'];?></a><br/>
- <div style="width:50px; height:50px; border:none; background:url('/habr/weather/img/<?php echo $day['image']['0'];?>.png') no-repeat;background-size:cover;"></div>
- <?php
- echo '<a title="Днем">'.$day['temp_day'].'°</a> <a title="Ночью">'.$day['temp_night'].'°</a><br/>
- '.$day['weather_type']['0'].'<br/>
- '.$day['pressure']['0'].' мм<br/>
- '.$day['humidity']['0'].' %<br/>
- '.$day['wind_speed']['0'].' м/с
- </td>';
- }
- }
- ?>
- </tr>
- </tbody>
- </table>
- </div>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement