You may want to provide your website users with a way to add an event to their calendar. This can be accomplished using a dropdown menu created in your HTML that contains links to either download a VCard (for Outlook and iCalendar) or to URLs for online services (such as Google Calendar, Yahoo! Calendar and Outlook Online).

We start out with a very simple barebones HTML document that loads Bootstrap 3 and jQuery. Bootstrap 3 isn’t strictly required, but we’re using it to style and script our dropdown menu. You could also use some other framework such as Foundation, or none at all and just create a simple dropdown menu with a <select> tag in your HTML.

 

The markup for our Bootstrap 3 dropdown menu is as follows:

As you can see, we’re referencing a lot of variables in those URLs. We use the rawurlencode() function to encode all non-alphanumeric characters except -_.~ as % followed by two hex digits. The calendars that require a VCard all link to a download.php script which will generate the VCard as a download to the user’s local drive.

The timestamps we return for iCalendar should be formatted so a date/time like January 2nd, 2015 at 1:00pm would be formatted as:

The portion before the T is the date, and the portion afterwards is the time. For Microsoft Outlook, we will also want to add a Z to the end of the timestamp, to signify that this is a UTC date/time stamp.

To set up our PHP code, replace the first line of this file with the following:

We use gmdate() instead of date() so we can add each date/time to the VCard as UTC time. To add a couple of extra styles to the dropdown menu, add the following <style> tag to the <head> of the document:

Next create the download.php document, which will generate our VCards, and add the following contents:

For the event details variable, we are replacing all instances of \n with \\n to escape the slashes. These will then be shown as \n in the event details field, instead of showing new lines (which will cause the event to not load properly for Outlook, and possibly other clients since that field should all be on one line in a VCard).

As you can see, with a little date parsing in our PHP, some simple HTML markup, and adequately researching the URL formats to use we can implement a way for our users to add our events to their calendars.

The full code is available as a git repository at https://github.com/websightdesigns/addevent