W3docs

How can I use PHP to dynamically publish an ical file to be read by Google Calendar?

Here's an example of how you can use the iCalcreator library to create an iCal file and output it for download:

Here's an example of how you can use the iCalcreator library to create an iCal file and output it for download:

Example of using the PHP iCalcreator library to create an iCal file and output it for download

<?php

// Verify the library file exists to prevent fatal errors
if (!file_exists('iCalcreator.class.php')) {
    die('Error: iCalcreator library file not found.');
}

require_once 'iCalcreator.class.php';

// Create a new iCal instance
$ical = new vcalendar();

// Set the calendar properties
$ical->setProperty('method', 'PUBLISH');
$ical->setProperty("x-wr-calname", "My Calendar");
$ical->setProperty("X-WR-CALDESC", "Events for my calendar");
$ical->setProperty("X-WR-TIMEZONE", "UTC");

// Add an event with dynamic dates
$event = &$ical->newComponent('vevent');
$start = new DateTime('2022-12-15 09:00:00', new DateTimeZone('UTC'));
$end = new DateTime('2022-12-15 17:00:00', new DateTimeZone('UTC'));

$event->setProperty('dtstart', $start->format('Ymd\THis\Z'), ['VALUE' => 'DATE-TIME', 'TZID' => 'UTC']);
$event->setProperty('dtend', $end->format('Ymd\THis\Z'), ['VALUE' => 'DATE-TIME', 'TZID' => 'UTC']);
$event->setProperty('summary', 'Christmas Day');
$event->setProperty('description', 'Celebrate Christmas with family and friends');
$event->setProperty('location', 'My House');

// Prepare and output the iCal file for download
$ical->prepareCalendar();
header('Content-Type: text/calendar; charset=utf-8');
header('Content-Disposition: attachment; filename="calendar.ics"');
echo $ical->returnCalendar();

?>

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

This script verifies the library file exists, creates a new instance of the vcalendar class, sets calendar properties, and adds an event using dynamic DateTime objects for reliable timezone handling. It then calls $ical->prepareCalendar() to ensure proper formatting, sets the appropriate headers, and outputs the file. Now you can provide a link to this script file on your website and your users can import the events into their Google Calendar by clicking on the link.