PHPで祝日表示付きカレンダーの作成。
PHPのPEARライブラリを使って、祝日の表示を加えたカレンダーの作成方法です。
カレンダーの作成には「Calendar」ライブラリ、祝日の取得には「Date_Holidays_Japan」ライブラリを利用しています。
| 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 | <?php require_once("Calendar/Month/Weekdays.php"); require_once("Date/Holidays.php"); $current_year = date("Y"); $current_month = date("n"); $calMonth = new Calendar_Month_Weekdays($current_year, $current_month, 0);//第3引数の0は週の最初を日曜に $calMonth->build(); $ja = "data/Date_Holidays_Japan/lang/Japan/ja_JP.xml"; $dh = &Date_Holidays::factory("Japan", $current_year, "ja_JP"); $dh->addTranslationFile($ja, "ja_JP"); $holidays = array(); //祝日の月日をキーに祝日名を配列に格納 foreach ($dh->getHolidays() as $value) { 	$holidays[$value->getDate()->format("%m%d")] = $value->getTitle(); } echo "<h2>".$current_year."年".$current_month."月"."</h2>\n"; echo "<table class=\"calendar\">\n";  echo "<thead>\n";  echo "<tr><th>日</th><th>月</th><th>火</th><th>水</th><th>木</th><th>金</th><th>土</th></tr>\n";  echo "</thead>\n";  echo "<tbody>\n";  while ($day = $calMonth->fetch()) {  	if ($day->isFirst()) { 		echo '<tr>'; 	} 	if ($day->isEmpty()) {  		echo "<td> </td>"; 	} else {  		$date = sprintf("%02d",$day->thisMonth()).sprintf("%02d",$day->thisDay()); 		if (array_key_exists($date, $holidays)) { 			echo "<td class=\"holiday\">";//祝日のとき 		} else if ($day->isFirst()) { 			echo "<td class=\"sun\">";//週の最初(日曜)のとき 		} else if ($day->isLast()) { 			echo "<td class=\"sat\">";//週の最後(土曜)のとき 		} else { 			echo "<td>"; 		} 		echo "<span class=\"day\">".$day->thisDay()."</span>"; 		//祝日に該当する月日の場合、祝日名を出力 		if (array_key_exists($date, $holidays)) { 			echo "<span class=\"holiday\">".$holidays[$date]."</span>"; 		} 		echo "</td>"; 	}  	if ($day->isLast()) {  		echo "</tr>\n"; 	}  }  echo "</tbody>\n"; echo "</table>\n"; ?> | 
あらかじめ祝日の月日、名称を配列に格納しておき、カレンダー生成のループの中で、祝日の判定を行っています。