下準備
- Google APIs ConsoleでCalendar APIのステータスをONにする
- Google API keyを取得する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function get_holidays_this_month($year, $month){ | |
// 月初日 | |
$first_day = mktime(0, 0, 0, intval($month), 1, intval($year)); | |
// 月末日 | |
$last_day = strtotime('-1 day', mktime(0, 0, 0, intval($month) + 1, 1, intval($year))); | |
$api_key = 'YOUR API KEY HERE'; | |
$holidays_id = 'outid3el0qkcrsuf89fltf7a4qbacgt9@import.calendar.google.com'; // mozilla.org版 | |
//$holidays_id = 'japanese__ja@holiday.calendar.google.com'; // Google 公式版日本語 | |
//$holidays_id = 'japanese@holiday.calendar.google.com'; // Google 公式版英語 | |
$holidays_url = sprintf( | |
'https://www.googleapis.com/calendar/v3/calendars/%s/events?'. | |
'key=%s&timeMin=%s&timeMax=%s&maxResults=%d&orderBy=startTime&singleEvents=true', | |
$holidays_id, | |
$api_key, | |
date('Y-m-d', $first_day).'T00:00:00Z' , // 取得開始日 | |
date('Y-m-d', $last_day).'T00:00:00Z' , // 取得終了日 | |
31 // 最大取得数 | |
); | |
if ( $results = file_get_contents($holidays_url) ) { | |
$results = json_decode($results); | |
$holidays = array(); | |
foreach ($results->items as $item ) { | |
$date = strtotime((string) $item->start->date); | |
$title = (string) $item->summary; | |
$holidays[date('Y-m-d', $date)] = $title; | |
} | |
ksort($holidays); | |
} | |
return $holidays; | |
} |
9行目の $api_key = 'YOUR API KEY HERE';
って所を取得してきた Google API Key に書き換えてください。
このやり方非常に参考になりました。
日本の祝日ではなく、
Googleカレンダーに登録したスケジュール(一般公開)を表示するプログラムに変えるにはこのソースを少し変更したら出来ないでしょうか。
11行目の $holidays_id という変数に入れる値を変えれば、他のカレンダーからも取ってこれると思います。
OAuth用の長いクライアントIDを入れなければいけないのかと思っておりましたが、
カレンダーのIDを入れたところ動作しました!ありがとうございました。
かなり簡単にやりたいことが見つけられて助かりました。
私企業でなく公式機関がやって欲しい仕事ですよね、天下りが増えるだけな気もする・・のが残念ですが。
多分、このままだと月末に祝日が制定されると取得できない気がします。
月末の祝日って聞いたことがないので運用上問題ないとの判断かもしれませんが。
下記七行目のあたりを ’-1 day’ から ’0 day’ などにすれば大丈夫かなと思います。
// 月末日
$last_day = strtotime(‘-1 day’, mktime(0, 0, 0, intval($month) + 1, 1, intval($year)));
全然問題なかったらすいません。
一応テストしましたが、へっぽこなのであまり自信はありません。