Google Calendar API を使用して祝日を取得する方法について。
Google 側の仕様が結構変わっているようで、ネット上に落ちてる情報が古かったので載せておきます。
(今回紹介する Google Calendar API の利用例は、コチラの記事にて 【PHP】期間内の祝日・定休日などを含んだ日付情報を取得する)
1.API キーの発行
Google Cloud Platformにアクセスして「Google API を利用する」を選択する。
他者にAPIキーを利用されないように「HTTP リファラー」などで、APIキーに制限をかける。
「HTTP リファラー」で、APIキーに制限をかけた場合、同一ドメイン内であれば、Google Map などにも使いまわせます。
2.Google Calendar API を使用して祝日を取得する関数を用意
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | /** * 期間内の祝日を取得する * * @param string $date_start 開始日(Y-m-d) * @param string $date_end 終了日(Y-m-d) * @param string $google_api_key Google API Key * @return array 祝日の配列 */ function getHolidayList( $date_start , $date_end , $google_api_key ) { // カレンダーID $calendar_id = urlencode( 'ja.japanese#holiday@group.v.calendar.google.com' ); $max_results = 100; $startDate = new DateTime( $date_start ); $endDate = new DateTime( $date_end ); $param_start = $startDate ->format( 'Y-m-d' ) . 'T00:00:00Z' ; $param_end = $endDate ->format( 'Y-m-d' ) . 'T00:00:00Z' ; $url .= '?key=' . $google_api_key ; $url .= '&timeMin=' . $param_start ; $url .= '&timeMax=' . $param_end ; $url .= '&maxResults=' . $max_results ; $url .= '&orderBy=startTime' ; $url .= '&singleEvents=true' ; $ch = curl_init(); curl_setopt( $ch , CURLOPT_URL, $url ); curl_setopt( $ch , CURLOPT_RETURNTRANSFER, true); curl_setopt( $ch , CURLOPT_SSL_VERIFYPEER, false); curl_setopt( $ch , CURLOPT_REFERER, $ref ); $result = curl_exec( $ch ); curl_close( $ch ); if ( empty ( $result ) === true) { return array (); } $json = json_decode( $result ); if ( empty ( $json ->items) === true) { return array (); } $holiday_list = array (); foreach ( $json ->items as $item ) { $holiday_list [] = $item ->start-> date ; } return $holiday_list ; } |
ざっくり解説
カレンダーIDは、Googleカレンダーの設定画面から確認可能です。
https://calendar.google.com/calendar/r
API に制限をかけたので「CURLOPT_REFERER」でリファラーを設定する必要があります。
3.実際に使ってみる
使用例は以下の記事にて。
「2」で紹介している「getDateInfo」関数内で使用しています。
【PHP】期間内の祝日・定休日などを含んだ日付情報を取得する)