Google
Calendar is a free and fully featured web based calendar solution. The
calendar information is kept private by default, but you can also make
a calendar public. This is great if you have a list of public events
that you want to manage and display. Here we will use PHP to retrieve
the events from a public Google Calendar and display them on a web page.
Log into Google Calendar and create a new calendar using the link highlighted in the screenshot below.
Make sure you tick Make this calendar public.
Add some events to the public calendar.
Click the drop down arrow next to the public calendar and click Calendar Settings.
Make a note of the Calendar ID. We will need this ID later on.
Download a copy of the Google Data PHP Client Library from here. Extract it and add a reference to the library from your PHP.INI file, using the include_path option.
We need to know the URL to contact in order to query the calendar. This is where the Calendar ID from step 1 is used.
$calendarID = "7p1r13309m2tpe7h1p3o4o7u34@group.calendar.google.com";
$googleFeedsURL = "http://www.google.com/calendar/feeds/" . $calendarID . "/public/full";
The following code loads the Zend PHP library and a number of classes that we will use later on.
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_Query');
Zend_Loader::loadClass('Zend_Gdata_Calendar');
Here we use the URL defined in step 3 to get the calendars data and store it in a variable called eventFeed.
$query = new Zend_Gdata_Query($googleFeedsURL);
$gdClient = new Zend_Gdata_Calendar();
$eventFeed = $gdClient->getCalendarEventFeed($query);
To display the calendar details we just need to loop over the events contained in the eventFeed variable. Notice that we use the date_parse_from_format function to break down the date string returned by the web service. This allows us to display the date in a more readable form.
foreach ($eventFeed as $event)
{
echo '<p><a href="' . $event->link[0]->href . '">';
echo $event->title->text;
echo '</a></p>';
foreach ($event->when as $when)
{
$startData = date_parse_from_format("Y-m-d\TH:i:s:uO", $when->startTime);
$endData = date_parse_from_format("Y-m-d\TH:i:s:uO", $when->endTime);
echo '<p>' .
$startData['day'] . '-' .
$startData['month'] . '-' .
$startData['year'] . ' ' .
$startData['hour'] . ':' .
sprintf("%02d", $startData['minute']) .
'<br/>' .
'To' .
'<br/>' .
$endData['day'] . '-' .
$endData['month'] . '-' .
$endData['year'] . ' ' .
$endData['hour'] . ':' .
sprintf("%02d", $endData['minute']) .
'</p>';
}
}
You
could modify this code to display events between certain days, or
filter events based on a string. The benefit of using Google Calendar
as the back end database is that entering and maintaining a calendar is
a piece of cake. The only code you have to write is the code above to
display the events on your site.