Google Calendar API v3を利用して祝日を取得してみた
- March 30th, 2013
カレンダーに祝日を表示する必要があり、Google CalendarのAPIを利用してみたのでメモしておきます。
祝日を取得するなら、PEARのDate_Holidays_Japanを利用しても良かったんだけど、CakePHP内で利用するのが面倒そうだったので、Google Calendar APIを使ってみました。
まずは、Google Calendar APIを利用できるように下準備を
- Google APIs ConsoleでCalendar APIのステータスをONにする
- Google API keyを取得する
- 参考ページ(Googleカレンダーを使って祝日の情報を取得する - DoboWiki)
※参考ページでは、Google Calendar APIのバージョン2と3の取得方法が記載されているので、バージョン3を参考にしてください。
Google APIs Consoleで必要な設定を行ったら、お決まりのURLを入力すれば、JSONデータが返されるので取得完了です。
今回のサンプルコードは、PHPでの取得方法を記載しています。
<?php
// Google Calendar API v3 (Holiday)
$holiday_type = urlencode('ja.japanese#holiday@group.v.calendar.google.com');
$google_api_key = '{Google API Key}';
$time_min = date('Y-m-01'). 'T00:00:00Z'; // RFC3339形式
$time_max = date('Y-m-01', strtotime('1month')). 'T00:00:00Z';
$google_holiday_jp_url = 'https://www.googleapis.com/calendar/v3/calendars/'. $holiday_type. '/events'
. '?key='. $google_api_key // Google API key
. '&timeMin='. $time_min // 取得開始日
. '&timeMax='. $time_max // 取得終了日(終了日の前日までしか取得しない)
. '&maxResults=20' // 取得数
. '&orderBy=startTime' // 並び順
. '&singleEvents=true'; // ???
$result = file_get_contents($google_holiday_jp_url);
$result = json_decode($result);
if (!empty($result->items)) {
foreach ($result->items as $value) {
$title = (string) $value->summary;
$date = (string) $value->start->date;
$holidays[$date] = $title;
}
}
?>- March 30th, 2013
