Advertisement
Guest User

Untitled

a guest
Aug 7th, 2014
987
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. //Определение  города
  3.     function getGeo($ip){
  4.         if(!filter_var($ip, FILTER_VALIDATE_IP, array('flags' => FILTER_FLAG_IPV4)))
  5.         return FALSE;
  6.         $get = file_get_contents("http://ipgeobase.ru:7020/geo?ip={$ip}");
  7.         $xml = simplexml_load_string($get);
  8.         $city = isset($xml->ip->city) ? strtolower($xml->ip->city) : '';
  9.         return $city;
  10. }
  11.  
  12. class weather{
  13.  
  14. private     $cache_dir;
  15. public      $city_id;
  16. private     $noon; //Время дня. По-умолчанию 4 - основная часть дня 11:00-20:00
  17. private     $night; //Время ночи. По-умолчанию 5
  18.  
  19.     //Инициализируем класс
  20.     public function __construct(){
  21.    
  22.     $this->cache_dir=$_SERVER['DOCUMENT_ROOT'].'/habr/cache/weather/';
  23.     $this->noon=4;
  24.     $this->night=5;
  25.    
  26.     if(isset($_SESSION['weather_city'])){$cityname=$_SESSION['wether_city'];} //Берем название города из сессии
  27.     else{$cityname=getGeo($_SERVER['REMOTE_ADDR']); }// Получаем название города по автоопределению
  28.    
  29.     $cities=json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'].'/habr/weather/YandexCities.txt'));
  30.        
  31.         if(isset($cities->$cityname)){
  32.             $this->city_id=$cities->$cityname;
  33.         } else {
  34.             $this->city_id=$cities->{'Махачкала'};
  35.         }
  36.     }
  37.    
  38.    
  39.    
  40.    
  41.         //Возвращает плюс, минус или ноль в зависимости от температуры
  42.     public function checkZeroMark($temperature){
  43.         if($temperature>0){
  44.             return '+'.$temperature;
  45.         } elseif ($temperature<0){
  46.             return '-'.$temperature;
  47.         }
  48.     return $temperature;
  49.     }
  50.    
  51.    
  52.     //Получаем погоду для определенного города
  53.     public function getCityWeather(){
  54.         $_LANG['MONTHS']    =   array(
  55.                     'Jan'=>'январь', 'Feb'=>'февраль', 'Mar'=>'март',
  56.                     'Apr'=>'апрель', 'May'=>'май','Jun'=>'июнь',
  57.                     'Jul'=>'июль','Aug'=>'август', 'Sep'=>'сентябрь',
  58.                     'Oct'=>'октябрь','Nov'=>'ноябрь','Dec'=>'декабрь');
  59.                    
  60. $_LANG['WEEKDAYS']  =   array(
  61.                     'Sunday'=>'воскресенье', 'Monday'=>'понедельник',
  62.                     'Tuesday'=>'вторник', 'Wednesday'=>'среда',
  63.                     'Thursday'=>'четверг', 'Friday'=>'пятница',
  64.                     'Saturday'=>'суббота');
  65.        
  66.        
  67.         $city_cache=$this->{cache_dir}.$this->{city_id};
  68.         //Если время последнего изменения кэш файла меньше шести минут, возвращаем данные из кэша
  69.         if(file_exists($city_cache) && filemtime($city_cache)>time()-360){
  70.             $jsoned_weather=json_decode(file_get_contents($city_cache),TRUE);
  71.            
  72.         } else { //Если кэш отсутствует, получаем данные с яндекса
  73.                 $weather=simplexml_load_file('http://export.yandex.ru/weather-ng/forecasts/'.$this->city_id.'.xml');
  74.            
  75.                 if($weather!=null){
  76.                
  77.                         //Погода на семь дней
  78.                         for($i=1; $i<=7; $i++)
  79.                         {
  80.                             if($weather->day[$i]!=null){
  81.                                 $days['sevendays'][]=array(
  82.                                 'weekday' => strtr(date('l', strtotime($weather->day[$i]->attributes()->date)), $_LANG['WEEKDAYS']),
  83.                                 'data'=>strtr(date("j M",strtotime($weather->day[$i]->attributes()->date)), $_LANG['MONTHS']),
  84.                                 'temp_day' => $this->checkZeroMark($weather->day[$i]->day_part[$this->noon]->temperature),
  85.                                 'temp_night' => $this->checkZeroMark($weather->day[$i]->day_part[$this->night]->temperature),
  86.                                 'weather_type' => $weather->day[$i]->day_part[$this->noon]->weather_type,
  87.                                 'wind_speed' => $weather->day[$i]->day_part[$this->noon]->wind_speed,
  88.                                 'humidity' => $weather->day[$i]->day_part[$this->noon]->humidity,
  89.                                 'pressure' => $weather->day[$i]->day_part[$this->noon]->pressure,
  90.                                 'image' => $weather->day[$i]->day_part[$this->noon]->{'image-v3'}
  91.                                 );
  92.                             }
  93.                         }
  94.                    
  95.                     //Погода на сегодня
  96.                     $days['today']=array(
  97.                     'weekday' => strtr(date('l'), $_LANG['WEEKDAYS']),
  98.                     'data'=>strtr(date('j M Y, G:i'), $_LANG['MONTHS']),
  99.                     'temperature' => $this->checkZeroMark($weather->fact->temperature),
  100.                     'weather_type' => $weather->fact->weather_type,
  101.                     'wind_speed' => $weather->fact->wind_speed,
  102.                     'humidity' => $weather->fact->humidity,
  103.                     'pressure' => $weather->fact->pressure,
  104.                     'water_temp' => $this->checkZeroMark($weather->fact->water_temperature),
  105.                     'sunrise' => $weather->day->sunrise,
  106.                     'sunset' => $weather->day->sunset,
  107.                     'image' => $weather->fact->{'image-v3'},
  108.                     'city'=>$weather->attributes()->city,
  109.                     'country' => $weather->attributes()->country
  110.                     );
  111.                                
  112.                     file_put_contents($city_cache, json_encode($days));
  113.                     $jsoned_weather=json_decode(file_get_contents($city_cache), TRUE);
  114.                 } else{
  115.                         return null;
  116.                 }
  117.         }
  118.         return $jsoned_weather;
  119.        
  120.     }
  121.    
  122.    
  123.    
  124.    
  125.  
  126.    
  127.    
  128.    
  129. }
  130.  
  131.  
  132. $weather=new weather;
  133. $jsoned_weather=$weather->getCityWeather();
  134. $today=$jsoned_weather['today'];
  135. $sevendays=$jsoned_weather['sevendays'];
  136. ?>
  137.  
  138.  
  139.  
  140.  
  141. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" >
  142. <head>
  143. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
  144. <title>Погода от Яндекса</title>
  145. </head>
  146. <body>
  147.  
  148. <style>
  149. #weather{
  150. margin-top:-10px;
  151. background: url('/habr/weather/sun.jpg') no-repeat;
  152. background-size:cover;
  153. padding:10px;
  154. min-height:300px;
  155. width:790px;
  156. }
  157.  
  158. #weather table{
  159. width:790px;
  160. background-color:RGBa(0,0,0,0.4);
  161. color:white;
  162.  
  163. }
  164.  
  165. #weather td{
  166. vertical-align:middle;
  167. }
  168. </style>
  169. <div id="weather">
  170. <table cellpadding="0" cellspacing="0" border="0">
  171.  <tbody>
  172.     <tr>
  173.         <td style="padding:10px 13px 0;">
  174.             <span style="font-size:24px;"><?php echo $today['city']['0'].', '.$today['country']['0'];?></span>
  175.         </td>
  176.     </tr>
  177.     <tr>
  178.         <td style="padding:0 13px;">
  179.             сегодня <?php echo $today['weekday'].', '.$today['data'];?>
  180.         </td>
  181.     <tr >
  182.         <td>
  183.             <img style="margin-left:20px; width:70px; height:70px;"  src="/habr/weather/img/<?php echo $today['image']['0'];?>.png"
  184.             title="<?php echo $today['weather_type']['0']; ?>">
  185.             <span style="font-size:100px; font-family:Arial;"><?php echo $today['temperature'];?>&deg;</span>
  186.         </td>
  187.         <td style="height:70px; width:190px;">
  188.             <?php echo $today['weather_type']['0'];?><br/>
  189.             <?php if($today['water_temp']!=null){
  190.                 echo 'температура воды '.$today['water_temp'].'&deg';
  191.             }
  192.             ?>
  193.         </td>
  194.         <td style="padding-left:5px;">
  195.         <?php
  196.         echo '  Атм. давление '.$today['pressure']['0'].' мм. рт.ст.<br/>
  197.             Влажность '.$today['humidity']['0'].'% <br/>
  198.             Скорость ветра '.$today['wind_speed']['0'].' м/с <br/>
  199.             Рассвет '.$today['sunrise']['0'].' / Закат '.$today['sunset']['0'];
  200.         ?>
  201.         </td>
  202.     </tr>
  203.  </tbody>
  204. </table>
  205. <br/>
  206. <table cellpadding="0" cellspacing="0" border="0">
  207.  <tbody style="text-align:center;">
  208.     <tr>
  209.  <?php
  210.  if($sevendays!=false){
  211.     foreach($sevendays as $day){
  212.         ?>
  213.         <td style="width:100px; vertical-align:top; text-align:left; padding:2px 5px;">
  214.                 <a title="<?php echo $day['weekday'].'">'.$day['data'];?></a><br/>
  215.             <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>
  216.             <?php
  217.             echo '<a title="Днем">'.$day['temp_day'].'&deg;</a> <a title="Ночью">'.$day['temp_night'].'&deg;</a><br/>
  218.             '.$day['weather_type']['0'].'<br/>
  219.             '.$day['pressure']['0'].' мм<br/>
  220.             '.$day['humidity']['0'].' %<br/>
  221.             '.$day['wind_speed']['0'].' м/с
  222.         </td>';
  223.     }
  224. }
  225. ?>
  226.     </tr>
  227.  </tbody>
  228. </table>
  229. </div>
  230.  
  231. </body>
  232. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement