Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Display Google Calendar events on your PHP Web site with XPath

XPath and SimpleXML provide the right balance between readability and verbosity in XML-parsing APIs

PJ Cabrera (pjcabrera@pobox.com), Software Engineer, Freelance Writer
P.J. Cabrera
P.J. Cabrera is a developer specializing in Ruby on Rails e-commerce and content-management systems development. His interests include Ruby on Rails and open source scripting languages and frameworks, agile development practices, mesh networks, compute clouds, XML-parsing and processing technologies, microformats for more semantic Web content, and research into innovative uses of Bayesian filtering and symbolic processing for improved information retrieval, question answering, text categorization, and extraction. Read his weblog at pjtrix.com/blawg/.

Summary:  Google Calendar and other online calendaring applications provide simple centralized systems where online communities can maintain event calendars and community members can get information about upcoming events. But many organizations prefer to display event calendars on their community portals, forums, or blogs. They often copy event calendar information from online calendaring applications onto their Web sites, reducing the effectiveness of centrally managing events online. Google Calendar provides an integration application program interface (API) that provides a good solution to this problem. Find out how to use XPath to extract and display Google Calendar data on your PHP Web site.

Date:  27 Nov 2007
Level:  Intermediate
Also available in:   Russian  Japanese  Vietnamese

Activity:  94593 views
Comments:  

While freelancing as a Web developer some years ago, I developed a PHP-powered Web portal for a community of owners and fans of a particular model of automobile (typically called a car club, they are very popular where I live). Some years before contacting me, some of the car club leaders had learned basic Web skills and created a Web site on their own. As the site grew, it accumulated a large number of pages, some stale, where separate event calendar information was posted. Since the site's main purpose was to inform the general public and community members of activities, these pages were littered with event calendar information.

Over time, these disparate snapshots of the community's event calendar grew out of sync. Some pages still had sidebars announcing events long gone. Even with proper management and efficient Web design, maintaining separate copies of event calendar data on separate pages is a time-consuming and error-prone process. Instead of the car club Web site working for them, they found themselves working hard for their Web site. They contacted me in the hope that I could show them a better way.

They wanted a site with forums where club members could discuss their favorite cars and a central news page for the latest event write-ups and announcements. On this news page, they could inform their growing membership of events, such as get-togethers, caravan rides to landmarks and around the countryside, and general member meetings where they discussed membership dues and budgeting considerations. More importantly, they didn't want to have to maintain a dozen or more copies of the event calendar anywhere. They wanted to enter the event calendar in one place and be able to access that information from anywhere else on the site.

Google Calendar and the Google data API

Online calendaring applications like Google Calendar provide a solution. By centralizing the display and management of events, Google Calendar users can share and maintain event data at one site, eliminating one of many possible sources of errors from the event organization process. Community members can visit the online calendar to keep abreast of upcoming events and activities without the confusion caused by out-of-date event information on separate Web pages. It seems online calendaring applications are the ideal solution.

While developing the club's Web site with the Drupal content-management system (see Resources), I recommended that the club's leaders use Google Calendar to maintain the event calendar. At first, the idea caught on, and they reported great productivity because it was easy to use the Drupal administrative front end to update the events sidebar I had created for them. But over time, the club's success meant more events to announce, and editing the events sidebar went from being fun and easy to an aggravating chore.

The Google data API and its access to Google Calendar event data provided a way out of this predicament. The Google data API provides an implementation of the Atom Publishing Protocol (APP), a Web service API for reading and updating different types of documents and information. There are also third-party integration APIs for Microsoft® .NET, the Java™ programming language, Python, and PHP that encapsulate much of the Google data API functionality in a set of object-oriented wrapper classes.

After some research, I was able to extend the car club's Drupal site with an always up-to-date events sidebar that pulled the latest event calendar data from the Google Calendar account.


The Google Calendar feed

The Google data API provides a number of Atom feeds containing the documents and information for many of the Web services offered by Google. Google Calendar is no exception, providing a number of feeds encapsulating the majority of Google Calendar data. There are HTTP-authenticated and public feeds. To retrieve and interact with authenticated feeds, the HTTP client needs to provide authentication information along with the HTTP GET request. The authenticated feeds also have the ability to update the Google Calendar account with HTTP POST requests. HTTP clients using authenticated feeds can add and remove events, subscribe to and unsubscribe from calendars, and create and delete calendars from the Google account.

The Google Calendar API provides feeds to access all the individual calendars a user has access to from the Google Calendar GUI. This consists of calendars owned by the user, calendars owned by someone else but that the user has subscribed to, and calendars the user has imported in a read-only state. These calendars each have their own authenticated private and public event feeds, where the individual events in the calendar are listed. This article focuses on public event feeds.

Making your Google Calendar feed public

The public event feed of a Google Calendar calendar, of which an account can have many, is obtained by signing in to the Google Calendar application, selecting the calendar you are interested in processing, and clicking the small down arrow by the calendar's name. After you click this arrow, a menu displays next to the feed's name. Select Calendar Settings, which is circled in Figure 1.


Figure 1. Google Calendar drop-down menu for a selected calendar


Then the Google Calendar application goes to a page where you can select various calendar settings, such as the time zone for the events and the name of the calendar. One important option for public feeds is whether the calendar itself is a public or shared calendar. To make your calendar shared and retrievable through the public events feed, click the Change sharing settings option, shown in Figure 2.


Figure 2. Changing a calendar's visibility to shared or public


The page will go to the Share this calendar tab where you can choose to Share all information on this calendar with everyone. A series of pop-up questions will display, asking whether you really mean to make your calendar public. Answer Yes, and don't forget to save your settings by clicking Save at the bottom of the tab. Click Back to Calendar to continue adding events to your calendar.

Examining a Google Calendar feed

For an example of a Google Calendar feed, refer to the full.xml file in the code sample provided in the Download section. I also provide a link to a dummy feed used in the code examples throughout this article (see Resources).

Event feeds contain various elements that describe an event, such as the event title, a description, and when and where the event is taking place. Google Calendar also manages a list of people invited to an event through a list of e-mails to which the event details are sent whenever it is updated. If these e-mail addresses represent Google Calendar users, they can respond to the invitation through the application, and the event also holds their attendance status. Integration with attendance details is beyond the scope of this article, which focuses on basic event information, such as event title and when and where the event is taking place. Listing 1 is an event entry from the sample feed.


Listing 1. Sample Google Calendar event feed entry: ID and time stamps
                
    <entry>
	    <id>
            http://www.google.com/calendar/feeds/foss.sanjuan%40gmail.com/public/full/
            s19o15ve3nn209gv5qf6c43ao4
        </id>
        <published>2007-08-12T15:45:40.000Z</published>
        <updated>2007-08-12T15:53:37.000Z</updated>
        ...
        ...

The id element provides a unique Uniform Resource Identifier (URI) that identifies this event inside the Google Calendar system. It not only contains a unique number but also identifies the feed from which it was retrieved. The published and updated elements use the RFC 3339 time-stamp format. The updated element indicates when the event was last edited or, in the case of a new event, when it was created.

After the id, published, and updated elements come elements with more human-readable information, as shown in Listing 2. This information can be displayed in a sidebar or events page.


Listing 2. Sample Google Calendar event feed entry: Title, author, and status
                
        ...
        ...

        <title type="text">Linux Install Fest</title>
        ...
        ...

        <author>
            <name>Open Source San Juan</name>
            <email>foss.sanjuan@gmail.com</email>
        </author>
        ...
        ...

        <gd:eventStatus value="http://schemas.google.com/g/2005#event.confirmed"/>
        ...
        ...

The title element is a simple string identifying the event. It does not need to be unique. The author element consists of a name and email element. The event's author is the Google Calendar user who entered the event into the calendar. With authenticated feeds and write-access permissions set accordingly, Google Calendar users other than the calendar's owner can create events on another user's calendar. Table 1 describes the possible values for the status element.


Table 1. Possible values for gd:eventStatus element
ValueDescription
http://schemas.google.com/g/2005#event.cancelledThe event is canceled.
http://schemas.google.com/g/2005#event.confirmedThe event is confirmed.
http://schemas.google.com/g/2005#event.tentativeThe event is tentatively scheduled.

Now come the elements that describe the time and place where the event is taking place, as shown in Listing 3.


Listing 3. Sample Google Calendar event feed entry: When and where
                
        ...
        ...

        <gd:when startTime="2007-08-03T16:00:00.000-04:00" 
            endTime="2007-08-03T19:00:00.000-04:00"/>
        <gd:where 
            valueString="Guaynabo Public High School Auditorium, Guaynabo, PR"/>
    </entry>

The when element contains two attributes: a start and end time for the event, both in RFC 3339 time-stamp format. The where element valueString attribute is fully searchable from the Google Calendar application and through the API. Google Calendar and the Google data API do not support searching by individual elements. Instead, they do a full-text search on string elements, such as title, author, and description, and the where element valueString attribute. As you'll see later, the exception is that the Google data API does support setting ranges of start dates to limit which events are included in query results.

Limiting the contents of the Google Calendar feed

To support the retrieval of precise sets of data, the Google data API supports the concept of query parameters in the HTTP GET request. Using these parameters, the Google data API client can specify the maximum number of entries to return (with the max-results parameter), what element to use to sort the entries in the feed (through the orderby parameter), and inclusive start and end times for the range of entries to return (through the start-min and start-max parameters). These last two parameters refer to the date range of event start times to be included in the result set of events. start-min refers to the begin date in the range, and start-max refers to the end of the range. Both are expressed in RFC 3339 time-stamp format.

Finally, you can make recurring events easier to parse by including the singleevents parameter in the query string. When the singleevents parameter has a value of true, recurring events are specified in the feed as if they were distinct single events. Otherwise, recurrent events include a <gd:recurrence> element that contains recurrence rules in iCal format. The iCal format and how to parse it are beyond the scope of this article.

Listing 4 is what the event feed URL looks like with all the query parameters added. It has been redacted to break the long URL into several lines for readability.


Listing 4. Sample Google Calendar feed URL with query parameters
                
    http://www.google.com/calendar/feeds/foss.sanjuan%40gmail.com/public/full?
    max-results=25&
    singleevents=true&
    orderby=starttime&
    start-min=2007-05-22T09%3A58%3A47-04%3A00&
    start-max=2007-11-06T09%3A58%3A47-04%3A00


Parsing the Google Calendar feed with PHP

Now that I've discussed the elements of the Google Calendar event feed and how to query the feed to obtain the entries you're interested in, I'll explore the ways to parse the feed and display it on a page. PHP provides several XML APIs you can use to retrieve a list of event entries and pick out the title, date, time, and location for each event. I'll begin with the Document Object Model (DOM) API.

Parsing the feed with DOM

The XML DOM API is a standard XML-parsing API, and it is the most commonly used when programming XML applications. The use of the DOM API is beyond the scope of this article, but I will go over an example program that parses a Google Calendar event feed and explain some of the DOM API's benefits and drawbacks.

One benefit of the XML DOM API is that it is fast. It loads the entire XML document into memory, and retrieval of elements from the XML document all occurs in memory. While this is inefficient for large XML files, it is acceptable for XML files of only 2 or 3 MB.

Another benefit of the XML DOM API is its readability. Parsing XML with DOM consists of commands to open the XML document and retrieve specific elements from the document in a hierarchical fashion. It's almost like English, telling PHP to "get elements with the 'entry' tag name." Listing 5 is an example to explain what I mean.


Listing 5. Parsing Google Calendar event feed with DOM API
                
<?php 
    $confirmed = 'http://schemas.google.com/g/2005#event.confirmed';

    $three_months_in_seconds = 60 * 60 * 24 * 28 * 3;
    $three_months_ago = date("Y-m-d\Th:i:sP", time() - $three_months_in_seconds);
    $three_months_from_today = date("Y-m-d\Th:i:sP", time() + $three_months_in_seconds);

    $feed = "http://www.google.com/calendar/feeds/foss.sanjuan%40gmail.com/" . 
        "public/full?orderby=starttime&singleevents=true&" . 
        "start-min=" . $three_months_ago . "&" .
        "start-max=" . $three_months_from_today;

    $doc = new DOMDocument(); 
    $doc->load( $feed );

    $entries = $doc->getElementsByTagName( "entry" ); 

    foreach ( $entries as $entry ) { 

        $status = $entry->getElementsByTagName( "eventStatus" ); 
        $eventStatus = $status->item(0)->getAttributeNode("value")->value;

        if ($eventStatus == $confirmed) {
            $titles = $entry->getElementsByTagName( "title" ); 
            $title = $titles->item(0)->nodeValue;

            $times = $entry->getElementsByTagName( "when" ); 
            $startTime = $times->item(0)->getAttributeNode("startTime")->value;
            $when = date( "l jS \o\f F Y - h:i A", strtotime( $startTime ) );

            $places = $entry->getElementsByTagName( "where" ); 
            $where = $places->item(0)->getAttributeNode("valueString")->value;

            print $title . "\n"; 
            print $when . " AST\n"; 
            print $where . "\n"; 
            print "\n"; 
        }
    }
?>

In this code sample, you set up the feed URL with the parameters needed, open the feed, then get all the event entries in a DOMNodeList, which you can process with the foreach iterator. For each event entry, you compare the value attribute of the gd:eventStatus element with the known value for confirmed events. Notice that you don't need to specify the gd: prefix for the element tag. The PHP DOM API understands name spaces, and you need to drop the gd: prefix or the parser won't find the element you want.

If the event entry is confirmed, you retrieve the title, gd:when, and gd:where elements. The gd:when and gd:where elements require that you request specific attributes, such as startTime and valueString. You want to display event dates in a human-readable way and parse the gd:when element's startTime attribute to convert it into a long integer representing time. Then you pass this to the date function with a common display format.

One of the downsides of the DOM API is that it is somewhat verbose. While it is clear what the intent of each statement is because it matches the text description of the algorithm, it is not as terse a bundle of code as it could be. The getElementsByTagName and getAttributeNode methods for the DOMNode and DOMDocument classes add considerable bulk.

Parsing the feed with SAX

Another XML-parsing API available to PHP is the Simple API for XML (SAX) API. While the DOM API is readable and verbose, SAX can be terse and difficult to follow, even for experienced developers. The differences between SAX and DOM are that SAX does not load the entire XML document into memory, whereas DOM does. Efficient SAX processing code can be blazingly fast, and memory usage can be kept to a minimum and tailored for the specific needs of the application. With DOM, your memory requirements begin at the size of the biggest XML document processed in your application and go up from there.

Listing 6 is a segment of an example of SAX processing of the Google Calendar events feed. For the complete example, refer to the sax_sample.php script in the example scripts package provided in the Download section.


Listing 6. Parsing Google Calendar event feed with SAX API
                
    function startElement( $parser, $tagName, $attr )
    {
        global $g_entries, $g_tagName, $g_confirmed, $g_is_confirmed, 
            $g_in_entry, $g_in_originalevent;

        if ( $tagName == 'ENTRY' ) {
            if ($g_is_confirmed || count( $g_entries ) == 0) {
                $g_entries []= array();
            }
            $g_is_confirmed = false;
            $g_in_entry = true;
        }
        else if ($tagName == 'GD:EVENTSTATUS')
        {
            if ($attr['VALUE'] == $g_confirmed) {
                $g_is_confirmed = true;
            }
        }
        else if ($tagName == 'GD:WHEN' && $g_is_confirmed && 
            $g_in_originalevent == false)
        {
            $startTime = date( "l jS \o\f F Y - h:i A", strtotime($attr['STARTTIME']) );
            $g_entries[ count( $g_entries ) - 1 ]['when'] = $startTime;
        }
        else if ($tagName == 'GD:WHERE' && $g_is_confirmed)
        {
            $g_entries[ count( $g_entries ) - 1 ]['where'] = $attr['VALUESTRING'];
        }
        else if ( $tagName == 'GD:ORIGINALEVENT' ) {
            $g_in_originalevent = true;
        }
        $g_tagName = $tagName;
    }

    function endElement( $parser, $tagName ) 
    {
        global $g_tagName, $g_in_entry, $g_in_originalevent;

        if ( $tagName == 'ENTRY' ) {
            $g_in_entry = false;
        }
        else if ( $tagName == 'GD:ORIGINALEVENT' ) {
            $g_in_originalevent = false;
        }
        $g_tagName = null;
    }

    function textData( $parser, $text )
    {
        global $g_entries, $g_tagName, $g_in_entry;
        if ($g_tagName == 'TITLE' && $g_in_entry) {
            $g_entries[ count( $g_entries ) - 1 ]['title'] = $text;
        }
    }

This code shows the startElement, endElement, and textData functions, which are registered with the SAX parser engine in the SAX example script. This part of the code shows the processing for several elements of interest. The code gets quite complex because XML elements in SAX are read in order from top to bottom of the XML document. You can't check whether the current event entry is confirmed before you process some of the elements you want. For example, the gd:eventStatus element comes after the title element in an event. Another source of complexity is that the feed has a title element, and each entry also has a title element. You need to set a flag to let the code know whether you are reading the title element within the entry. There is also a gd:when element inside the gd:originalEvent element in recurrent events, which is not the gd:when element you are interested in. Without this state-checking logic, simple matching of element names produces the wrong output.

From this example, you can see two of the downsides of the SAX API: It is much more verbose than the DOM API and, when compared to the DOM sample code, the SAX parser is several times more complex.

Parsing the feed with the Zend Google API wrappers

Zend Technologies, in collaboration with Google, has extended the Zend Framework to provide a set of object-oriented classes for PHP that hide many of the details of the Google data API's Atom feeds, while providing support for all Google data information. These object-oriented classes have many benefits, including presenting the various Google data API documents as abstract objects with methods and simple parameters and hiding the details of the Atom feeds and HTTP protocol actions, such as GETs, PUTs, and POSTs. These classes also encapsulate the details of user authentication in the Google data API, making it simpler to write applications that support all features of the Google data API, such as creating and updating events from a third-party client.

While this simplifies development for developers who are not familiar with XML parsing and HTTP protocol details, the Zend Framework Google data API classes are not without their drawbacks. As shown in Listing 7, the code is verbose because many object constructors do not take parameters. Therefore, options have to be set through properties after an object is created.


Listing 7. Requesting and processing a Google Calendar event feed with the Zend PHP classes
                
<?php
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_Calendar');

$three_months_in_seconds = 60 * 60 * 24 * 28 * 3;
$three_months_ago = date("Y-m-d\Th:i:sP", time() - $three_months_in_seconds);
$three_months_from_today = date("Y-m-d\Th:i:sP", time() + $three_months_in_seconds);

// Create an instance of the Calendar service without authentication,
// for read-only access to a public feed
$service = new Zend_Gdata_Calendar();

$query = $service->newEventQuery();
$query->setUser('foss.sanjuan%40gmail.com');
$query->setVisibility('public');
$query->setProjection('full');
$query->setOrderby('starttime');
$query->setStartMin($three_months_ago);
$query->setStartMax($three_months_from_today);

// Retrieve the event list from the calendar server
try {
    $eventFeed = $service->getCalendarEventFeed($query);
} catch (Zend_Gdata_App_Exception $e) {
    echo "Error: " . $e->getResponse();
}

// Iterate through the list of events, outputting them as an HTML list
print "<ul>\n";
foreach ($eventFeed as $event) {
    print "<li>" . $event->title . "</li>\n";

	$startTime = $event->when->startTime;
    print "<li>" . date("l jS \o\f F Y - h:i A", strtotime( $startTime ) );

	// Google Calendar API's support of timezones is buggy
    print " AST</li>\n";

    print "<li>" . $event->where->valueString . "</li>\n";
}
print "</ul>\n";

One of the benefits of the Zend Google data API classes is that after the eventFeed object is retrieved, the elements and attributes of the feed can be traversed hierarchically as properties of the eventFeed object. This, in my opinion, allows for easier reading of the processing code because the various elements are organized in a similar fashion to how they are presented in the XML document. Attributes are also traversable in a hierarchical fashion from their parent elements, unlike DOMNode's getAttributeNode("attributeName")->value method.


Parsing with XPath and SimpleXML

I believe the SimpleXML API, with its support for querying XML documents using XPath, is one of the easiest XML-parsing APIs to use. It encapsulates the XML document as a hierarchical set of object properties of the loaded XML document. This is similar to how DOM returns DOMNode object instances that can be traversed hierarchically. Like DOM's DOMNode objects and unlike the Zend classes, an element's attributes need to be retrieved by calling the attributes() method. This returns an object that holds the attributes as object properties. Listing 8 presents all the logic necessary to parse and traverse a Google data API calendar feed with SimpleXML.


Listing 8. Parsing the Google Calendar event feed with XPath and SimpleXML
                
    $s = simplexml_load_file($feed); 

    foreach ($s->entry as $item) {
        $gd = $item->children('http://schemas.google.com/g/2005');

        if ($gd->eventStatus->attributes()->value == $confirmed) {
?>
            <font size=+1><b>
                <?php print $item->title; ?>
            </b></font><br>

<?php 
            $startTime = '';
            if ( $gd->when ) {
                $startTime = $gd->when->attributes()->startTime;
            } elseif ( $gd->recurrence ) {
                $startTime = $gd->recurrence->when->attributes()->startTime; 
            } 

            print date("l jS \o\f F Y - h:i A", strtotime( $startTime ) );
            // Google Calendar API's support of timezones is buggy
            print " AST<br>";
?>
            <?php print $gd->where->attributes()->valueString; ?>
            <br><br>

<?php
        }
    } ?>

One drawback to PHP's SimpleXML API is that it can be up to four times slower than DOM or SAX. This stems from the fact that SimpleXML creates the element and attribute nodes on the fly by exploiting the dynamic nature of PHP. Contrast this to the Zend Google data API classes, which define the element and attribute nodes in the class code. This makes hierarchical traversal of nodes with the Zend classes faster.

Another drawback to SimpleXML is its support for XML namespaces. To retrieve elements from a name space, the children() method needs to be called on an element. This returns an object with elements of that namespace as properties. DOM and the Zend classes provide better support by presenting all elements of all namespaces as individual hierarchically-traversable nodes of other elements.


Performance considerations and caching

When discussing XML parsing in PHP, I mentioned that SimpleXML could be many times slower than DOM or SAX parsing. My reason for choosing SimpleXML is that it's easier to use than SAX and makes for more readable XML-parsing code than DOM. SimpleXML's generation of element and attribute nodes on the fly as properties of other nodes makes for node traversal code that is almost as readable as the Zend Google data API classes.

However, the code sample provided in this article suffers from another problem: It asks for the Google Calendar event feed every time a user visits the page. If you place this sample in a sidebar on a PHP site, every time a visitor goes to any of your pages, the code downloads and parses the feed anew. This is rather wasteful, considering the calendar is probably not changing every hour or even every day. If your site is popular and draws 1,000 or more page hits per day (easily achievable with a popular forum of only 20-30 unique users), the feed is requested and processed for each page hit. The Google data API has clear terms of service that explain that this kind of use is not permitted. Google can, and probably will, block your server's IP address if you abuse its terms of service. Worse, Google can cancel your account. Clearly, a more intelligent approach is called for.

There are several strategies you can implement to make the sample code work more intelligently and within the Google API terms of service. They all involve caching the information displayed by the script and only requesting processing of the whole feed if and when it has changed. An in-depth discussion of caching techniques is beyond the scope of this article, but I will discuss them briefly to give you an idea of how the script can be improved.

One technique involves using HTTP request headers to check if the Google data API feed has changed. Google data services set the Last-Modified response header based upon the value of the <atom:updated> element in the returned information. The script, upon being called the first time, can save the output generated by processing the feed to an HTML file. The script can then store the value of the <atom:updated> time stamp in a database record. Next time any user requests to see the event calendar, the client retrieves the time stamp and sends it back in the If-Modified-Since request header to avoid retrieving the feed again if it hasn't changed.

If the content hasn't changed since the time indicated in the If-Modified-Since header, the Google data service returns a 304 (Not Modified) HTTP response. Because this means the event data has not changed, the script can then include the previously generated HTML file. If the feed has changed, the Google data service returns a 200 (OK) HTTP response. In this case, the script regenerates the new content for the HTML file, sets the database record to the new time-stamp value in the <atom:updated> element, and includes the newly generated HTML file.

Saving a single time stamp to a database is quite a bit of overkill, but PHP does not support application-level variables like Microsoft Active Server Pages (ASPs), Microsoft ASP.NET, Java servlets, and JavaServer Pages (JSPs) do, at least not out of the box. A similar solution is using shared memory. Not all installations of PHP support shared memory because it can be a security risk. Another possible caching alternative, especially if your PHP application is running in a Web-server cluster, is memcached, a clustered memory-caching service originally authored by the creators of LiveJournal and now improved extensively by the developers of FaceBook.


Conclusion

Google Calendar provides a central Web application front end from which an organization and its leaders can maintain and publish an event calendar for their members and the public at large. The Google data API provides Atom feeds and the Atom Publishing Protocol for retrieving, querying, updating, and creating events and other information using Google Calendar and almost all the other Google applications.

Using XPath, you can automatically keep a Web site's display of upcoming events up to date by querying the Google data API event feeds and parsing its entries for relevant details among the entries' elements. While XPath is not the fastest XML API in the PHP toolkit, it is among the easiest to use when you have a well-documented XML document on hand. You can use caching to reduce the impact of XPath's relatively slow performance.



Download

DescriptionNameSizeDownload method
Sample PHP codeos-php-xpath.google-calendar-api.zip4KB HTTP

Information about download methods


Resources

Learn

  • Learn more about the Drupal content-management system at its Web site.

  • The Google Calendar APIs and Tools Overview contains a good introduction to the possible uses of the Google Calendar API and links to more thorough documentation of all parts of the API.

  • PHP.net is the central resource for PHP developers.

  • Check out the "Recommended PHP reading list."

  • Browse all the PHP content on developerWorks.

  • Expand your PHP skills by checking out IBM developerWorks' PHP project resources.

  • To listen to interesting interviews and discussions for software developers, check out developerWorks podcasts.

  • Using a database with PHP? Check out the Zend Core for IBM, a seamless, out-of-the-box, easy-to-install PHP development and production environment that supports IBM DB2 V9.

  • Stay current with developerWorks' Technical events and webcasts.

  • Check out upcoming conferences, trade shows, webcasts, and other Events around the world that are of interest to IBM open source developers.

  • Visit the developerWorks Open source zone for extensive how-to information, tools, and project updates to help you develop with open source technologies and use them with IBM's products.

  • Watch and learn about IBM and open source technologies and product functions with the no-cost developerWorks On demand demos.

Get products and technologies

Discuss

About the author

P.J. Cabrera

P.J. Cabrera is a developer specializing in Ruby on Rails e-commerce and content-management systems development. His interests include Ruby on Rails and open source scripting languages and frameworks, agile development practices, mesh networks, compute clouds, XML-parsing and processing technologies, microformats for more semantic Web content, and research into innovative uses of Bayesian filtering and symbolic processing for improved information retrieval, question answering, text categorization, and extraction. Read his weblog at pjtrix.com/blawg/.

Report abuse help

Report abuse

Thank you. This entry has been flagged for moderator attention.


Report abuse help

Report abuse

Report abuse submission failed. Please try again later.


developerWorks: Sign in


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


Rate this article

Comments

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Open source, XML
ArticleID=270615
ArticleTitle=Display Google Calendar events on your PHP Web site with XPath
publish-date=11272007
author1-email=pjcabrera@pobox.com
author1-email-cc=