[php] openweathermap.org의 API를 이용한 현재 기상정보 보여주기

2015. 1. 29. 15:43 from Dev/php

예전에 openweathermap.org에서 제공하는 기상 정보를 이용하는 방법에 대해서 간단하게 올렸었습니다. (링크)

무료로 이용할 수 있는 날씨 정보 API가 별로 없는데, 이곳 서비스는 안정적으로 잘 이용하고 있습니다.

오늘은 간단하게 객체화 시킨 소스를 보여드리겠습니다. 언제나 그렇듯이 잘못된 부분이나 더 개선할 부분이 있으면 알려주세요. ^^



class Weather {

	const API_URL_CURRENT = "http://api.openweathermap.org/data/2.5/weather?lat=37.56826&lon=126.977829&units=metric&APPID=<발급받은 아이디>";
	const API_URL_FORECAST = "http://api.openweathermap.org/data/2.5/forecast/daily?lat=37.56826&lon=126.977829&cnt=5&units=metric&APPID=<역시 발급받은 아이디>";

	public static function get_current_weather() {
		$c = curl_init(self::API_URL_CURRENT);
		$options = array(
			CURLOPT_HEADER => false,
			CURLOPT_RETURNTRANSFER => true
		);
		curl_setopt_array($c, $options);
		$data = curl_exec($c);
		curl_close($c);
		
		if (isset($data) && $data) {
			$data_obj = json_decode($data);
			$result = array(
				'current_temp' => $data_obj->main->temp,
				'temp_min' => $data_obj->main->temp_min,
				'temp_max' => $data_obj->main->temp_max,
				'desc' => $data_obj->weather[0]->main,
				'icon' => "http://openweathermap.org/img/w/{$data_obj->weather[0]->icon}.png",
				'status' => 'ok'
			);
			return $result;
		}
	}
	
	public static function get_weather_forecast() {
		$c = curl_init(self::API_URL_FORECAST);
		$options = array(
			CURLOPT_HEADER => false,
			CURLOPT_RETURNTRANSFER => true
		);
		curl_setopt_array($c, $options);
		$data = curl_exec($c);
		curl_close($c);
		
		return json_decode($data);
	}
}

$w = Weather::get_current_weather();
echo "現在 " . number_format($w['current_temp'], 1) . "℃";


php 파일을 만드신 다음에 원하는 곳에 include만 해주면 간단한 날씨 아이콘과 현재 기온이 그림처럼 출력됩니다.

위 예제는 서울을 기준으로 했으니 다른 도시라면 lat, lon을 바꾸어주셔야 합니다.


이미지 아이콘도 $w['icon']으로 이용하실 수 있습니다만, 이쁜 아이콘이 아니라 pass. ㅋㅋ



여기에 가시면 오픈소스 날씨 관련 아이콘이 있습니다

erikflowers/weather-icons



기상 예측에 대해서도 일단 정보를 가져오는 부분은 코딩을 해 놓았습니다. json 객체이니 보시고 입맛에 맞게 이용하시면 됩니다.

Posted by banasun :