Consuming Google Calendars with the Zend Framework

A couple of weeks ago, Google jumped into the online calendar space by launching Google Calendar (um, beta). The application is chock-full of Ajaxy goodness and plenty of features, but I’m here to talk about what you can do with your calendar data behind the scenes. Using some handy tools from the Swiss Army Knife that is the Zend Framework, I’ll show you how to pull data from your Google Calendar into your site. Just for kicks, I’ll also throw in a caching layer to keep things fast and reduce the network traffic between your server and Google.

Our Tools

Since we don’t want to request the calendar feed from Google every time we run our script, we can use the Zend_Cache module to store the file locally, and only update it at a given interval. Zend_Cache is still in incubation, but in my testing I found it plenty stable to handle this task. Zend_Cache is developed by the author of PEAR’s Cache_Lite package.

Lucky for us, Google Calendar exports data in Atom format. That means we can use the Zend_Feed module to parse our cached XML file into a PHP object. No fussy XML wrangling today, so sorry.

The Code

For this example, I’ll assume you have a Google Calendar with some data in it, and that you know your feed’s URL. To find the URL, log into your calendar and click "Settings." Then click the "Calendars" tab followed by the name of the calendar you want to import. You should see two XML icons on the Calendar Details page. You can use either one, but the public feed will must be shared, and will contain different information based on what you decide to make public.

You can download the code example here.

Let’s take a look at the code. First, I’ll include the necessary Framework modules, define a helper function for date formatting, set my calendar URL, and set my cache options:

Next, I’ll check the cache to see if we have our file saved. If there isn’t one, or if it’s stale, we fetch it from Google and save it.

Note, if you want to save several different calendars, make sure you use a different cache identifier for each. I chose "GoogleCalendar" for my single feed.

Now that we have the XML feed stored in the variable $xml, we can create a Zend_Feed object:

Now it’s just a matter of displaying our calendar information on the page. Examine the Zend_Feed manual and the raw feed itself to see what fields you can pull and display. In my example I’m using a minimalistic output. You’ll notice a little weirdness from Google–for example all of my events seem to be located in "America/Los_Angeles" despite the actual location I set.

That’s all there is to it! Post a comment and let us know the cool stuff you are doing with Google Calendars on your own site.