PHP Calendar
This utility function creates an HTML calendar table. Each day cell only contains the day number which may be a hyperlink. Example output:
| Sun | Mon | Tue | Wed | Thu | Fri | Sat |
|---|---|---|---|---|---|---|
| 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 |
The CSS code for this particular style.
The PHP code:
/*
* Draws a standard XHTML calendar with optional links for each day.
*
* Copyright (C) 2007 Clint Bellanger. Released under the GPL.
*
* @param $year The 4-digit numeric year
* @param $month The 2-digit numeric month. 1=Jan.
* @param $day_links String array of hyperlink URIs indexed by day of month
*/
function display_calendar($year, $month, $day_links) {
if ($month < 1 || $month > 12) return false;
// setup
$caption=jdmonthname(cal_to_jd(CAL_GREGORIAN,$month,1,$year),0) . " " . $year;
$starting_day_of_week=jddayofweek(cal_to_jd(CAL_GREGORIAN,$month,1,$year),0);
$days_in_month = cal_days_in_month(CAL_GREGORIAN,$month,$year);
$day_of_week = 0; // 0=Sun through 6=Sat, keep track of our layout position
// begin display
echo "<table class=\"calendar\">\n";
if ($caption != '') echo " <caption>" . $caption . "</caption>\n";
echo " <tr><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th>"
. "<th>Fri</th><th>Sat</th></tr>\n";
echo " <tr>";
// if first day is not Sunday, skip empty spaces to reach correct position
for ($skip=1;$skip<=$starting_day_of_week;$skip++) {
echo "<td></td>";
$day_of_week++;
}
for ($day=1; $day<=$days_in_month; $day++) {
echo "<td>";
// caller-specified link for this day
if (isset($day_links[$day])) {
echo "<a href=\"" . $day_links[$day] . "\">";
}
echo $day;
if (isset($day_links[$day])) echo "</a>";
echo "</td>";
$day_of_week++;
// if at a new sunday, start on the next week/row
if ($day_of_week == 7) {
$day_of_week = 0;
echo "</tr>\n";
if ($day < $days_in_month) echo " <tr>";
}
}
if ($day_of_week > 0) echo "</tr>\n";
echo "</table>\n";
return true;
} // end display_calendar()
Clint Bellanger is a developer for PFunked.
This article is released under the terms of the Creative Commons Share-Alike License. The source code listed above is released under the terms of the GNU Public License