如果想要在網站中,加入天氣報報. 

 

Yahoo 提供了一個免費的API. 

https://developer.yahoo.com/weather/#php

 

超級方便實用的....     

 

但是偶爾還是會凸鎚, (一年來凸鎚一天, 資料抓不回來,檔案內容是空)    我的做法是. 把抓回來的資料存到文字檔中, 然後讀文字檔中的本機資料. 

一小時更新一次!!  

 

 

PS. 最近温差大,  早上人家說不準...只好改成十分鐘啦!! 

 

 

function wyahoo($n='',$city='Kaohsiung',$unit='c')   //預設城市高雄,預設單位攝氏,要撈的資訊
{
   //第一次先把xml讀回主機 再抓xml檔案讀 速度比較快 預設 1天每小時更新一次

   $filename = 'upload/xml/wyahoo'.date('YmdH').  ceil((int)date("i")/10) * 10  . $city.$unit.'.json';
   if(!file_exists($filename) or filesize($filename) < 1000){
      $BASE_URL = "http://query.yahooapis.com/v1/public/yql";
      $yql_query = 'select * from weather.forecast where woeid in (select woeid from geo.places(1) where text="' . $city. '")';
      $yql_query_url = $BASE_URL . "?q=" . urlencode($yql_query) . "&format=json";
      // Make call with cURL
      $session = curl_init($yql_query_url);
      curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
      $json = curl_exec($session);
      $fHandle = fopen($filename, "w");
      fwrite($fHandle, $json);
      fclose($fHandle);
    } else {
        $json = file_get_contents($filename);
    }

    // Convert JSON to PHP object
     $phpObj =  json_decode($json);

     //$phpObj->query->results->channel->wind->speed;

      //=(攝氏溫度×9) ÷5+32
      $txt=array('high'       => number_format(($phpObj->query->results->channel->item->forecast[0]->high -32) * 5 / 9,1), //高溫
                 'low'        => number_format(($phpObj->query->results->channel->item->forecast[0]->low -32) *5 / 9,1),//低溫
                 'speed'      => $phpObj->query->results->channel->wind->speed, //風速
                 'humidity'   => $phpObj->query->results->channel->atmosphere->humidity,//濕度
                 'visibility' => $phpObj->query->results->channel->atmosphere->visibility,//能見度
                 'sunrise'    => $phpObj->query->results->channel->astronomy->sunrise,//日出時間
                 'sunset'     => $phpObj->query->results->channel->astronomy->sunset,//日落時間
                 'text'       => $phpObj->query->results->channel->item->forecast[0]->text
                );

      if($n=='') return $txt;
      else{
        if(isset($txt[$n])) return $txt[$n];
          else return '';
        }


}


arrow
arrow
    全站熱搜

    peeress 發表在 痞客邦 留言(0) 人氣()