Search by

calendar / icsfile

ColonelMoutarde

This simple class generate a .ics file.

12.2.0 2026-11-14 11:47 UTC

README

SymfonyInsight

A dependency-free PHP library that generates iCalendar (.ics) files following RFC 5545: events, to-dos, journal entries and free/busy time, including invitations, replies and cancellations (iTIP, RFC 5546).

The library never writes an invalid file: when a value or a combination of properties breaks the standard, it throws an IcalendarException instead.

Upgrading? See UPGRADE.md. How the library is built and how to replace its parts: docs/ARCHITECTURE.md.

Table of contents

  1. Quick start
  2. Dates and timezones
  3. Recurring events
  4. Event details
  5. Several events in one calendar
  6. To-dos, journal entries and free/busy time
  7. Invitations (iTIP)
  8. Output
  9. Errors and RFC compliance
  10. API reference

Quick start

Installation

PHP 8.5 or later, no other dependency:

composer require calendar/icsfile

A first event

Each Ical object is one event (VEVENT). The setters are fluent and can be called in any order; getICAL() checks the whole event and returns the file.

<?php

require_once 'vendor/autoload.php';

use Ical\Exceptions\IcalendarException;
use Ical\Ical;

$paris = new \DateTimeZone('Europe/Paris');

try {
    $ical = new Ical()
        ->setUid('team-meeting-2025-06-10@example.com') // keep it to update the event later
        ->setSummary('Team meeting')
        ->setAddress('Room 4, Paris')
        ->setDateStart(new \DateTimeImmutable('2025-06-10 09:00', $paris)) // the only required date
        ->setDateEnd(new \DateTimeImmutable('2025-06-10 10:00', $paris))
        ->setFilename('team-meeting');

    $ical->addHeader();     // the browser downloads team-meeting.ics
    echo $ical->getICAL();
} catch (IcalendarException $exception) {
    echo $exception->getMessage();
}
BEGIN:VCALENDAR
PRODID:-//icalendar-generator//EN
VERSION:2.0
CALSCALE:GREGORIAN
BEGIN:VEVENT
UID:team-meeting-2025-06-10@example.com
DTSTAMP:20250601T080000Z
DTSTART:20250610T070000Z
DTEND:20250610T080000Z
SUMMARY:Team meeting
LOCATION:Room 4\, Paris
TRANSP:OPAQUE
SEQUENCE:0
END:VEVENT
END:VCALENDAR

Dates are written in UTC by default (09:00 in Paris is 07:00Z); DTSTAMP is the current time unless you call setDateStamp().

Common tasks

To…Use
Create an all-day eventsetAllDay(new \DateTimeImmutable('2025-12-25')) instead of setDateStart()
Repeat an eventsetRrule('FREQ=WEEKLY;COUNT=10')
Keep the local time (TZID)setTimezoneICal('Europe/Paris')->setAutoVtimezone(true), then setDateStart($date, normalizeToUTC: false)
Add a remindersetAlarmMinutesBefore(30)
Put several events in one filenew Calendar()->addEvent($first, $second)
Add to-dos, journal entries, free/busyCalendar::addTodo(), addJournal(), addFreeBusy()
Send an invitationsetOrganizer(), addAttendee(), setMethod(MethodEnum::REQUEST)
Reply to or cancel an invitationReplyToInvitation, CancelEvent, RescheduleOccurrence
Return the file from a framework$ical->toIcsFile() and HttpHeaders::forFile($file)
Get a fixed output in testsIcalGenerator::generate($ical, null, $clock, $uidGenerator)

Dates and timezones

Start, end and timestamp

SetterPropertyNotes
setDateStart()DTSTARTrequired, unless the event is an all-day event
setDateEnd()DTENDoptional, strictly after the start
setDuration()DURATIONinstead of setDateEnd(), never both, e.g. PT1H30M
setDateStamp()DTSTAMPdefaults to the current time, shared by the events of a file; always in UTC

UTC or local time

By default, dates are converted to UTC, whatever the timezone of the server:

$date = new \DateTimeImmutable('2025-10-02 10:00:00', new \DateTimeZone('Europe/Paris'));

$ical->setDateStart($date);                         // DTSTART:20251002T080000Z

To keep the local time, pass normalizeToUTC: false. The date is converted to the setTimezoneICal() timezone and written with a TZID. RFC 5545 requires the matching VTIMEZONE, so enable the automatic one or define it; without it, the date stays in UTC:

$ical->setTimezoneICal('Europe/Paris')->setAutoVtimezone(true)
    ->setDateStart($date, normalizeToUTC: false);   // DTSTART;TZID=Europe/Paris:20251002T100000

Floating time

A floating date has no Z nor TZID: it is the same clock time everywhere, e.g. an alarm clock at 07:00 (RFC 5545 §3.3.5). Pass floating: true; the clock time is kept as given and no VTIMEZONE is needed:

$ical->setDateStart(new \DateTimeImmutable('2025-01-06 07:00:00'), floating: true)
    ->setDateEnd(new \DateTimeImmutable('2025-01-06 07:30:00'), floating: true)
    ->setRrule('FREQ=DAILY;UNTIL=20250131T070000');
// DTSTART:20250106T070000
// DTEND:20250106T073000
// RRULE:FREQ=DAILY;UNTIL=20250131T070000
  • DTEND (and DUE for a to-do) must be floating if and only if DTSTART is.
  • RDATE, EXDATE, RECURRENCE-ID follow DTSTART; the UNTIL of the rule is a local date-time, without Z.
  • DTSTAMP, CREATED, LAST-MODIFIED and alarm date-times stay in UTC.

Automatic VTIMEZONE

setAutoVtimezone(true) (disabled by default) builds the VTIMEZONE from the PHP timezone database:

$ical = new Ical()
    ->setTimezoneICal('Europe/Paris')
    ->setAutoVtimezone(true)
    ->setDateStart(new \DateTimeImmutable('2025-06-10 09:00:00', $paris), normalizeToUTC: false)
    ->setRrule('FREQ=WEEKLY');
// BEGIN:VTIMEZONE
// TZID:Europe/Paris
// BEGIN:DAYLIGHT
// DTSTART:20250330T020000
// TZOFFSETFROM:+0100
// TZOFFSETTO:+0200
// TZNAME:CEST
// RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU
// END:DAYLIGHT
// ...
// DTSTART;TZID=Europe/Paris:20250610T090000
  • It covers the changes of time between the first and the last date of the event; an event recurring forever gets the rules without end.
  • It is only added when a date is written in local time. In a Calendar, one VTIMEZONE is written per timezone.

Manual VTIMEZONE

Define the VTIMEZONE yourself with the setVtimezone*() setters; it takes precedence over the automatic one:

$ical = new Ical()
    ->setTimezoneICal('Europe/Paris')
    ->setVtimezoneTzid('Europe/Paris')
    ->setVtimezoneStandardTzname('CET')
    ->setVtimezoneStandardTzoffsetfrom('+0200')
    ->setVtimezoneStandardTzoffsetto('+0100')
    ->setVtimezoneStandardDtstart('19701025T030000')
    ->setVtimezoneStandardRrule('FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10')
    ->setVtimezoneDaylightTzname('CEST')
    ->setVtimezoneDaylightTzoffsetfrom('+0100')
    ->setVtimezoneDaylightTzoffsetto('+0200')
    ->setVtimezoneDaylightDtstart('19700329T020000')
    ->setVtimezoneDaylightRrule('FREQ=YEARLY;BYDAY=-1SU;BYMONTH=3')
    ->setVtimezoneTzurl('https://example.com/tz/Europe-Paris.ics'); // optional TZURL
  • It is written only when its TZID is the setTimezoneICal() timezone and both periods have their Dtstart, Tzoffsetfrom and Tzoffsetto.
  • Offsets are ±HHMM[SS] (not -0000), Dtstart a local date-time YYYYMMDDTHHMMSS, the rule UNTIL a UTC date-time.
  • setIncludeVtimezone(false) disables both the manual and the automatic VTIMEZONE.

VTIMEZONE given as a whole

For more than one STANDARD and one DAYLIGHT period, give a whole TimezoneDefinition with setVtimezone(); it takes precedence over the setters above:

use Ical\Domain\ValueObject\{LocalDateTime, RecurrenceRule, TimezoneDefinition, TimezonePeriod, UtcOffset};

$ical->setTimezoneICal('America/New_York')->setVtimezone(new TimezoneDefinition(
    'America/New_York',
    [
        // isDaylight, onset (local time before the change), TZOFFSETFROM, TZOFFSETTO, TZNAME, RRULE
        new TimezonePeriod(true, new LocalDateTime('20070311T020000'), new UtcOffset('-0500'), new UtcOffset('-0400'), 'EDT',
            RecurrenceRule::forTimezoneObservance('FREQ=YEARLY;BYMONTH=3;BYDAY=2SU')),
        new TimezonePeriod(false, new LocalDateTime('20071104T020000'), new UtcOffset('-0400'), new UtcOffset('-0500'), 'EST',
            RecurrenceRule::forTimezoneObservance('FREQ=YEARLY;BYMONTH=11;BYDAY=1SU'),
            comments: ['Eastern Standard Time'], localizedNames: ['fr' => 'HNE']),
        // onsets given one by one (RDATE) instead of a rule
        new TimezonePeriod(true, new LocalDateTime('19740106T020000'), new UtcOffset('-0500'), new UtcOffset('-0400'), 'EDT',
            rdates: [new LocalDateTime('19750223T020000')]),
    ],
    lastModified: new \DateTimeImmutable('2005-08-09 05:00:00', new \DateTimeZone('UTC')),
));

Its TZID must be the setTimezoneICal() timezone; setVtimezone(null) removes it. In a Calendar, two events cannot give different definitions of the same TZID.

All-day events

Use setAllDay() instead of setDateStart() / setDateEnd() for whole days. The dates are written as DATE values:

$ical->setAllDay(new \DateTimeImmutable('2025-12-25'));
// DTSTART;VALUE=DATE:20251225
// DTEND;VALUE=DATE:20251226

// From June 28 to July 8 included
$ical->setAllDay(new \DateTimeImmutable('2025-06-28'), new \DateTimeImmutable('2025-07-08'));
// DTSTART;VALUE=DATE:20250628
// DTEND;VALUE=DATE:20250709

// Two weeks, as a DURATION instead of a last day
$ical->setAllDay(new \DateTimeImmutable('2025-08-01'))->setDuration('P2W');
// DTSTART;VALUE=DATE:20250801
// DURATION:P2W
  • The last day is included; DTEND is the day after, because RFC 5545 defines it as exclusive.
  • Only the calendar date of the given object counts: its time and timezone are ignored.
  • The duration is in days or weeks, and cannot be combined with a last day, setDateStart() or setDateEnd().

Recurring events

Recurrence rule (RRULE)

setRrule() takes the rule without the RRULE: prefix (RFC 5545 §3.3.10); an empty string removes it:

// Every Monday, 10 times
$ical->setRrule('FREQ=WEEKLY;BYDAY=MO;COUNT=10');

// Last working day of each month, until the end of 2025
$ical->setRrule('FREQ=MONTHLY;BYDAY=MO,TU,WE,TH,FR;BYSETPOS=-1;UNTIL=20251231T235959Z');

// Every December 25 (all-day event: UNTIL is a date)
$ical->setAllDay(new \DateTimeImmutable('2025-12-25'))->setRrule('FREQ=YEARLY;UNTIL=20301225');

The rule is checked part by part: FREQ first, no UNTIL with COUNT, values in range, no part that RFC 5545 forbids for the FREQ (e.g. BYWEEKNO without FREQ=YEARLY). UNTIL must have the type of the start date:

Start dateUNTIL
setDateStart() (UTC or TZID)UTC date-time 20251231T235959Z
setDateStart(…, floating: true)local date-time 20251231T235959
setAllDay()date 20251231, and no BYHOUR, BYMINUTE, BYSECOND

Excluded and additional occurrences (EXDATE, RDATE)

$ical->setDateStart(new \DateTimeImmutable('2025-01-06 09:00:00', $paris))
    ->setRrule('FREQ=WEEKLY;BYDAY=MO;COUNT=10')
    ->setExdates(                                                         // no meeting on these Mondays
        new \DateTimeImmutable('2025-01-13 09:00:00', $paris),
        new \DateTimeImmutable('2025-01-20 09:00:00', $paris),
    )
    ->setRdates(new \DateTimeImmutable('2025-01-08 09:00:00', $paris))   // an extra meeting on a Wednesday
    ->setRdatePeriods(Period::startingAt(new \DateTimeImmutable('2025-01-10 14:00:00', $paris), 'PT2H')); // with its own length
// RRULE:FREQ=WEEKLY;BYDAY=MO;COUNT=10
// RDATE:20250108T080000Z
// RDATE;VALUE=PERIOD:20250110T130000Z/PT2H
// EXDATE:20250113T080000Z,20250120T080000Z
  • Each call replaces the previous dates; call it without argument to remove them.
  • The dates are written in the form of the start date (UTC, TZID or DATE), sorted and without duplicates.
  • An EXDATE requires an RRULE or an RDATE. RDATE alone makes the event recurring.
  • A Period (Ical\Domain\ValueObject\Period) is Period::between($start, $end) or Period::startingAt($start, $duration); an all-day event cannot have periods.

Modifying one occurrence (RECURRENCE-ID)

To change one occurrence, add a second Ical to the calendar with the same UID and setRecurrenceId() set to the original start of the occurrence:

$calendar = new Calendar()->addEvent(
    new Ical()                                    // every Monday at 09:00
        ->setUid('weekly@example.com')
        ->setSummary('Weekly')
        ->setDateStart(new \DateTimeImmutable('2025-01-06 09:00:00', $utc))
        ->setDateEnd(new \DateTimeImmutable('2025-01-06 10:00:00', $utc))
        ->setRrule('FREQ=WEEKLY;BYDAY=MO;COUNT=10'),
    new Ical()                                    // except Monday 13, moved to Tuesday 14 at 14:00
        ->setUid('weekly@example.com')
        ->setSummary('Weekly (moved)')
        ->setDateStart(new \DateTimeImmutable('2025-01-14 14:00:00', $utc))
        ->setDateEnd(new \DateTimeImmutable('2025-01-14 15:00:00', $utc))
        ->setSequence(1)
        ->setRecurrenceId(new \DateTimeImmutable('2025-01-13 09:00:00', $utc)),
);
// RECURRENCE-ID:20250113T090000Z
  • setRecurrenceId($originalStart, thisAndFuture: true) also changes the following occurrences (RANGE=THISANDFUTURE).
  • An occurrence can be generated alone, e.g. to reply to it. With its main event in the same calendar, the main event must recur, and an occurrence cannot be modified twice.

Event details

Text, status and classification

use Ical\Enum\ClassificationEnum;
use Ical\Enum\StatusEnum;
use Ical\Enum\TransparencyEnum;

$ical
    ->setSummary('Project review')                 // SUMMARY
    ->setDescription("Agenda:\n- budget")          // DESCRIPTION
    ->setAddress('Room 4, Paris')                  // LOCATION
    ->setLanguage('fr')                            // LANGUAGE of the texts
    ->setStatus(StatusEnum::TENTATIVE)             // CONFIRMED, TENTATIVE, CANCELLED
    ->setTransparency(TransparencyEnum::OPAQUE)    // OPAQUE (busy, default) or TRANSPARENT (free)
    ->setClassification(ClassificationEnum::PRIVATE) // PUBLIC, PRIVATE, CONFIDENTIAL
    ->setUrl('https://example.com/events/42')
    ->setCategories('Meeting', 'Project, Alpha')
    ->setResources('PROJECTOR', 'EASEL')
    ->setPriority(2)                               // 1 (highest) to 9 (lowest), 0 undefined
    ->setGeo(48.856614, 2.352222)                  // latitude, longitude
    ->setComments('Bring the slides')              // one COMMENT line per value
    ->setContacts('Jim Dolittle, +1-919-555-1234') // one CONTACT line per value
    ->setCreated(new \DateTimeImmutable('2024-11-01 09:00:00'))
    ->setLastModified(new \DateTimeImmutable('2024-11-15 18:30:00'));
// CATEGORIES:Meeting,Project\, Alpha
// CONTACT:Jim Dolittle\, +1-919-555-1234
// GEO:48.856614;2.352222
// CREATED:20241101T080000Z
  • An empty string (or null) removes a property; setters taking a list replace the previous values. Two exceptions: SUMMARY is always written, and setTransparency(null) restores TRANSP:OPAQUE.
  • setDescription($text, $altRep) and setAddress($text, $altRep) take an optional ALTREP, the URI of e.g. an HTML version.
  • setLanguage() applies to SUMMARY, DESCRIPTION, LOCATION, COMMENT, CONTACT, CATEGORIES and RESOURCES.
  • setDuration() takes a positive duration (P1W, P2D, PT1H30M, no months nor years); Duration::fromDateInterval($interval)->value converts a \DateInterval.
  • setUrl() takes an absolute URI (RFC 3986). Dates (CREATED, LAST-MODIFIED) are written in UTC.

Identification (UID, SEQUENCE, PRODID)

  • setUid() gives the event a persistent identifier, so that calendar applications can update it. Without it, a random UID is generated on each export.
  • setSequence() is the revision number (default 0): increase it each time you send an updated version.
  • setProdId() names the application that generated the file:
$ical->setProdId('Bob Morane', 'Conference Calendar', 'FR'); // PRODID:-//Bob Morane//Conference Calendar//FR
$ical->setProdId('My Company', 'Booking App');               // PRODID:-//My Company//Booking App//EN

Without it, the PRODID is -//icalendar-generator//EN. CALSCALE:GREGORIAN is always written, the only value RFC 5545 allows.

Attachments and related components (ATTACH, RELATED-TO)

use Ical\Domain\ValueObject\Attachment;
use Ical\Domain\ValueObject\Relation;
use Ical\Enum\RelationTypeEnum;

$ical
    ->setAttachments(
        Attachment::fromUrl('https://example.com/agenda.pdf', 'application/pdf'),
        Attachment::fromContent(file_get_contents('slides.pdf'), 'application/pdf'), // written in base64
    )
    ->setRelatedTo(new Relation('project-2025@example.com'), new Relation('review@example.com', RelationTypeEnum::SIBLING));
// ATTACH;FMTTYPE=application/pdf:https://example.com/agenda.pdf
// ATTACH;FMTTYPE=application/pdf;ENCODING=BASE64;VALUE=BINARY:JVBERi0xLjQK…
// RELATED-TO;RELTYPE=PARENT:project-2025@example.com
// RELATED-TO;RELTYPE=SIBLING:review@example.com

A Relation points to a UID, with the type PARENT (default), CHILD or SIBLING. For a component of the same calendar, you can use the UID you gave it: it is replaced by its final UID.

Alarms (VALARM)

The simplest reminder displays "Reminder":

$ical->setAlarm(true);                                     // 15 minutes before
$ical->setAlarmMinutesBefore(30)->setAlarmRepeat(3, 10);   // 30 minutes before, repeated 3 times every 10 minutes

Other alarms are built with the Alarm factory matching their action:

use Ical\Domain\ValueObject\Alarm;
use Ical\Domain\ValueObject\AlarmTrigger;
use Ical\Domain\ValueObject\Email;

$ical->addAlarm(
    Alarm::display(AlarmTrigger::relative('-PT5M', relatedToEnd: true), 'Wrap up')->withRepeat(2, 'PT1M'),
    Alarm::audio(AlarmTrigger::at(new \DateTimeImmutable('2025-01-01 09:55:00', $paris)), 'https://example.com/bell.mp3'),
    Alarm::email(AlarmTrigger::relative('-P1D'), 'Tomorrow', 'Meeting tomorrow', new Email('alice@example.com')),
);
Factory or triggerWrites
Alarm::display($trigger, $description)ACTION:DISPLAY with its text
Alarm::audio($trigger, ?$soundUrl)ACTION:AUDIO, with the sound as ATTACH or the default sound
Alarm::email($trigger, $summary, $description, ...$emails)ACTION:EMAIL: subject, body and recipients (at least one)
->withAttachments(Attachment ...)the documents attached to an EMAIL alarm
->withRepeat($count, $interval)REPEAT and the DURATION between repetitions
AlarmTrigger::relative('-PT15M')TRIGGER:-PT15M: before (-) or after the start
AlarmTrigger::relative('-PT5M', true)TRIGGER;RELATED=END:-PT5M: relative to the end, which the event must have
AlarmTrigger::at($dateTime)TRIGGER;VALUE=DATE-TIME:…Z: an absolute time

Non-standard properties (X-*)

addXProperty() adds an X- property to an event or to a calendar, e.g. for the extensions read by some applications:

$ical
    ->addXProperty('X-ALT-DESC', '<p>Agenda, <b>budget</b></p>', ['FMTTYPE' => 'text/html'])
    ->addXProperty('X-MICROSOFT-CDO-BUSYSTATUS', 'BUSY');
// X-ALT-DESC;FMTTYPE=text/html:<p>Agenda\, <b>budget</b></p>
// X-MICROSOFT-CDO-BUSYSTATUS:BUSY

$calendar->addXProperty('X-WR-CALNAME', 'Conference');
  • The name starts with X- followed by letters, digits or dashes.
  • The value is escaped as text, unless a VALUE parameter gives another type (['VALUE' => 'URI']): it is then written as given, on one line.

Several events in one calendar

Add the events to a Calendar, which has the same getICAL(), toIcsFile(), setFilename() and addHeader() as Ical:

use Ical\Calendar;
use Ical\Ical;

$calendar = new Calendar()
    ->setProdId('Bob Morane', 'Conference Calendar', 'FR')
    ->setFilename('conference')
    ->addEvent(
        new Ical()->setUid('keynote-2025@example.com')->setSummary('Keynote')
            ->setDateStart(new \DateTimeImmutable('2025-06-10 09:00:00', $utc)),
        new Ical()->setUid('workshop-2025@example.com')->setSummary('Workshop')
            ->setDateStart(new \DateTimeImmutable('2025-06-10 14:00:00', $utc)),
    );

echo $calendar->getICAL();
  • The PRODID and METHOD of the calendar are used, those of the events are ignored.
  • Each event needs its own UID, unless it is an occurrence of a recurring event.
  • A VTIMEZONE used by several events is written once.

To-dos, journal entries and free/busy time

A Calendar also holds to-dos (VTODO), journal entries (VJOURNAL) and free/busy time (VFREEBUSY), from Ical\Domain\Entity:

use Ical\Domain\Entity\FreeBusy;
use Ical\Domain\Entity\Journal;
use Ical\Domain\Entity\Todo;
use Ical\Enum\FreeBusyTypeEnum;
use Ical\Enum\JournalStatusEnum;
use Ical\Enum\TodoStatusEnum;

$calendar = new Calendar()
    ->addTodo(
        new Todo()
            ->setUid('report@example.com')
            ->setSummary('Write the report')
            ->setStart(new \DateTimeImmutable('2025-01-06 09:00:00', $paris))
            ->setDue(new \DateTimeImmutable('2025-01-10 18:00:00', $paris))   // or setDuration('P4D')
            ->setStatus(TodoStatusEnum::IN_PROCESS)
            ->setPercentComplete(40)
            ->addAlarm(Alarm::display(AlarmTrigger::relative('-P1D', true), 'Due tomorrow')),
    )
    ->addJournal(
        new Journal()
            ->setUid('minutes-2025-01-06@example.com')
            ->setStart(new \DateTimeImmutable('2025-01-06'), allDay: true)
            ->setSummary('Weekly minutes')
            ->setDescription('Monday meeting')
            ->addDescription("1. Budget\n2. Hiring")                         // a journal entry can have several
            ->setStatus(JournalStatusEnum::FINAL),
    )
    ->addFreeBusy(
        new FreeBusy()
            ->setUid('alice-busy@example.com')
            ->setOrganizer('alice@example.com')
            ->setStart(new \DateTimeImmutable('2025-01-06 00:00:00', $utc))
            ->setEnd(new \DateTimeImmutable('2025-01-11 00:00:00', $utc))
            ->addBusyTime(Period::startingAt(new \DateTimeImmutable('2025-01-06 09:00:00', $utc), 'PT1H'), FreeBusyTypeEnum::BUSY_TENTATIVE),
    );
// BEGIN:VTODO … DTSTART:20250106T080000Z / DUE:20250110T170000Z / STATUS:IN-PROCESS / PERCENT-COMPLETE:40 … END:VTODO
// BEGIN:VJOURNAL … DESCRIPTION:Monday meeting / DESCRIPTION:1. Budget\n2. Hiring … END:VJOURNAL
// BEGIN:VFREEBUSY … FREEBUSY;FBTYPE=BUSY-TENTATIVE:20250106T090000Z/PT1H … END:VFREEBUSY
EntitySetters, in addition to those of the events with the same name
All threesetUid(), setDateStamp(), setLanguage(), setOrganizer(), addAttendee(), setComments(), setUrl(), addXProperty()
Todo and JournalsetStart($date, $allDay, $normalizeToUTC, $floating), setRrule(), setRecurrenceId(), setRdates(), setExdates(), setAttachments(), setRelatedTo(), setSummary(), setDescription(), setClassification(), setCategories(), setContacts(), setSequence(), setCreated(), setLastModified()
TodosetDue($date, $allDay, $normalizeToUTC, $floating), setDuration(), setCompleted(), setPercentComplete() (0 to 100), setPriority(), setStatus(TodoStatusEnum), setLocation(), setGeo(), setResources(), addAlarm()
JournalsetStatus(JournalStatusEnum) (DRAFT, FINAL, CANCELLED), addDescription($text, ?$altRep): a further DESCRIPTION, after the one of setDescription()
FreeBusysetStart(), setEnd(), setContact(), addBusyTime(Period, FreeBusyTypeEnum = BUSY)
  • setStart() and setDue() write a UTC date-time by default; with normalizeToUTC: false, the local time of the given date with its TZID, whose VTIMEZONE is always added; with allDay: true, a DATE; with floating: true, a floating time.
  • A to-do has either a DUE (after DTSTART, of the same type) or a DURATION (which requires a DTSTART), not both.
  • An RRULE, RDATE, EXDATE or RECURRENCE-ID requires a DTSTART. Modified occurrences work as for events.
  • The dates of free/busy time are written in UTC; its FREEBUSY lines are grouped by type, sorted and without duplicates.
  • Each component needs its own UID, different from those of the events.

Invitations (iTIP)

Set the organizer, the attendees and an iTIP method (RFC 5546) so that Outlook, Gmail or Apple Calendar handle the file as an invitation:

use Ical\Domain\Entity\Attendee;
use Ical\Domain\ValueObject\Email;
use Ical\Enum\AttendeeRoleEnum;
use Ical\Enum\MethodEnum;
use Ical\Enum\ParticipationStatusEnum;

$ical = new Ical()
    ->setUid('team-meeting-2025@example.com')
    ->setSummary('Team meeting')
    ->setDateStart(new \DateTimeImmutable('2025-06-10 09:00:00', $utc))
    ->setOrganizer('boss@example.com', 'The Boss')
    ->addAttendee(
        new Attendee(new Email('john@example.com'), 'John Doe', AttendeeRoleEnum::REQ_PARTICIPANT, ParticipationStatusEnum::NEEDS_ACTION, rsvp: true),
        new Attendee(new Email('jane@example.com'), 'Jane Doe', AttendeeRoleEnum::OPT_PARTICIPANT),
    )
    ->setMethod(MethodEnum::REQUEST);

$ical->addHeader(); // Content-Type: text/calendar; charset=utf-8; method=REQUEST
echo $ical->getICAL();
// METHOD:REQUEST
// ORGANIZER;CN=The Boss:mailto:boss@example.com
// ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;CN=John Doe:mailto:john@example.com
// ATTENDEE;ROLE=OPT-PARTICIPANT;CN=Jane Doe:mailto:jane@example.com

Organizer

setOrganizer($email, $name, $sentBy, $directory, $language) writes the ORGANIZER; only the email is required. An event, a to-do or a journal entry with attendees must have an organizer (RFC 5545 §3.8.4.3), even without a method; otherwise getICAL() throws An ATTENDEE requires an ORGANIZER.

The name is quoted and encoded when needed (setOrganizer('jean@example.com', 'Dupont, "Jean"') → ORGANIZER;CN="Dupont, ^'Jean^'":mailto:jean@example.com).

Attendees

new Attendee(Email $email, ...) takes optional named arguments:

ArgumentPropertyValues
nameCNany text
roleROLEAttendeeRoleEnum: CHAIR, REQ_PARTICIPANT, OPT_PARTICIPANT, NON_PARTICIPANT
participationStatusPARTSTATParticipationStatusEnum: NEEDS_ACTION, ACCEPTED, DECLINED, TENTATIVE, DELEGATED; COMPLETED, IN_PROCESS for to-dos only
rsvpRSVPtrue when a reply is expected
calendarUserTypeCUTYPECalendarUserTypeEnum: INDIVIDUAL, GROUP, RESOURCE, ROOM, UNKNOWN
members, delegatedTo, delegatedFromMEMBER, DELEGATED-TO, DELEGATED-FROMlists of Email
sentBy, directory, languageSENT-BY, DIR, LANGUAGEEmail, Url, Language

An argument left to null is not written (calendar applications use the RFC 5545 default). An email can only be added once to an event.

Methods and their rules

setMethod(MethodEnum) sets the iTIP method; its rules are checked by getICAL():

MethodUseRules for an event
PUBLISHShare an event, no reply expectedORGANIZER, no ATTENDEE
REQUESTInvite, or update an invitation (same UID, higher SEQUENCE)ORGANIZER, at least one ATTENDEE, STATUS not CANCELLED
REPLYAnswer of an attendee (same UID)ORGANIZER, exactly one ATTENDEE with a PARTSTAT, no alarm
CANCELCancel the event, or remove the listed attendeesORGANIZER, at least one ATTENDEE, STATUS absent or CANCELLED, no alarm
  • Only PUBLISH accepts several events with different UIDs; with the other methods, the events of a Calendar must be a recurring event and its occurrences.
  • REQUEST-STATUS (setRequestStatuses(new RequestStatus('2.0', 'Success'))) is only allowed in a REPLY.
  • To-dos, journal entries and free/busy time follow the similar rules of RFC 5546 §3.3 to §3.5, with Calendar::setMethod(); a message holds one type of component. The details are in docs/ARCHITECTURE.md.

Replying, cancelling, rescheduling

The use cases of Ical\Application\Itip build the iTIP message from an existing event without modifying it, and return an IcsFile. They take an ExportCalendar:

use Ical\Application\ExportCalendar;
use Ical\Application\Itip\{CancelEvent, ReplyToInvitation, RescheduleOccurrence, UninviteAttendees};
use Ical\Enum\ParticipationStatusEnum;
use Ical\Infrastructure\{PhpTimezoneDefinitionProvider, RandomUidGenerator, Rfc5545Serializer, SystemClock};

$exportCalendar = new ExportCalendar(new Rfc5545Serializer(), new PhpTimezoneDefinitionProvider(), new SystemClock(), new RandomUidGenerator());

// An attendee accepts: METHOD:REPLY with this attendee only
$file = new ReplyToInvitation($exportCalendar)->reply($meeting, 'alice@example.com', ParticipationStatusEnum::ACCEPTED);

// The organizer cancels the event, or one occurrence: METHOD:CANCEL, STATUS:CANCELLED, SEQUENCE + 1
$file = new CancelEvent($exportCalendar)->cancel($meeting);
$file = new CancelEvent($exportCalendar)->cancel($meeting, new \DateTimeImmutable('2025-01-13 09:00:00', $utc));

// The organizer removes attendees: METHOD:CANCEL for them only, SEQUENCE + 1
$file = new UninviteAttendees($exportCalendar)->uninvite($meeting, 'cancellation', 'bob@example.com');

// The organizer moves one occurrence: METHOD:REQUEST with the moved occurrence, SEQUENCE + 1
$file = new RescheduleOccurrence($exportCalendar)->reschedule(
    $meeting,
    new \DateTimeImmutable('2025-01-13 09:00:00', $utc), // original start of the occurrence
    new \DateTimeImmutable('2025-01-14 14:00:00', $utc), // new start (the length is kept)
);
  • The new SEQUENCE is in the message only: store it on your event with setSequence().
  • reply() and uninvite() reject an email that is not an attendee of the event.

Output

Text encoding

  • Text values are escaped (\, ;, , and line breaks); control characters are removed.
  • All text must be valid UTF-8, otherwise getICAL() throws, naming the property.
  • Lines longer than 75 octets are folded without splitting a UTF-8 character; lines end with CRLF.

Downloading the file (HTTP headers)

addHeader() sends the headers with PHP's header(), before the output:

$ical->setFilename('Réunion équipe')->addHeader();
echo $ical->getICAL();
// Content-Type: text/calendar; charset=utf-8
// Content-Disposition: attachment; filename="R_union _quipe.ics"; filename*=UTF-8''R%C3%A9union%20%C3%A9quipe.ics

With a framework, get the file as an IcsFile (content, method, filename) and its headers from HttpHeaders:

use Ical\Infrastructure\HttpHeaders;

$file = $ical->toIcsFile();          // or $calendar->toIcsFile()
return new Response($file->content, 200, HttpHeaders::forFile($file));
  • The Content-Type carries the iTIP method when there is one (; method=REQUEST).
  • The filename gets the .ics extension (calendar.ics when empty); characters that could inject a header are removed.
  • addHeader($send) passes each header line to the $send closure instead of header(), e.g. in tests.

Clock and UID generator

Without setDateStamp() or setUid(), the current time and a random UID are used. Replace them to get a fixed output, e.g. in your tests:

use Ical\Application\ClockInterface;
use Ical\Application\UidGeneratorInterface;
use Ical\IcalGenerator;

$clock = new class implements ClockInterface {
    public function now(): \DateTimeImmutable
    {
        return new \DateTimeImmutable('2025-01-01 08:00:00', new \DateTimeZone('UTC'));
    }
};
$uidGenerator = new class implements UidGeneratorInterface {
    public function generate(string $domain): string
    {
        return 'fixed-uid@' . $domain;
    }
};

$ics = IcalGenerator::generate($ical, null, $clock, $uidGenerator);   // DTSTAMP:20250101T080000Z, UID:fixed-uid@example.com
$ics = IcalGenerator::generateCalendar($calendar, $clock, $uidGenerator);

ClockInterface::now() has the signature of PSR-20: a PSR-20 clock can be wrapped in a few lines.

Errors and RFC compliance

All errors are Ical\Exceptions\IcalendarException, whose message starts with the method that rejected the value:

new Email('foo'); // Ical\Domain\ValueObject\Email::__construct --> Invalid email 'foo' !
  • A setter throws when its value is invalid (email, timezone, URL, recurrence rule, duration, priority…).
  • getICAL(), toIcsFile() and IcalGenerator throw when properties do not fit together, since the setters can be called in any order: missing DTSTART, end before the start, both an end and a duration, UNTIL of another type than the start, EXDATE without recurrence, alarm related to a missing end, attendees without organizer, iTIP method rules, duplicate UIDs, invalid UTF-8…

Every generated file therefore complies with RFC 5545 (and RFC 5546 for the iTIP methods). The reference files of tests/stubs/ are checked by two independent validators (iCalendar.org and iCal4j, run by make validate); the list of the checked rules is in docs/ARCHITECTURE.md.

Not supported: the iTIP methods ADD, REFRESH, COUNTER and DECLINECOUNTER, IANA properties other than the X- ones, the TIME value type.

API reference

All setters return the object itself, so they can be chained. Most have a matching getter (getDateStart(), getRrule(), …), defined by Ical\Domain\Interface\EventInterface.

Ical

TopicMethods
DatessetDateStart(DateTimeInterface $date, bool $normalizeToUTC = true, bool $floating = false), setDateEnd(…), setDateStamp(DateTimeInterface), setDuration(string), isDateStartFloating(), isDateEndFloating()
TimezonesetTimezoneICal(string), setAutoVtimezone(bool), setIncludeVtimezone(bool)
Manual VTIMEZONEsetVtimezone(?TimezoneDefinition), setVtimezoneTzid(string), setVtimezoneTzurl(string), setVtimezone{Standard,Daylight}{Tzname,Tzoffsetfrom,Tzoffsetto,Dtstart,Rrule}(string)
All-daysetAllDay(DateTimeInterface $firstDay, ?DateTimeInterface $lastDay = null), isAllDay(), getAllDayStart(), getAllDayEnd()
RecurrencesetRrule(string), setExdates(DateTimeInterface ...), setRdates(DateTimeInterface ...), setRdatePeriods(Period ...), setRecurrenceId(?DateTimeInterface $originalStart, bool $thisAndFuture = false)
IdentificationsetUid(string), setSequence(int), setProdId(string $organisation, string $product, string $language = 'EN')
DetailssetSummary(string), setDescription(string, ?string $altRep = null), setAddress(string, ?string $altRep = null), setLanguage(?string), setStatus(StatusEnum), setTransparency(?TransparencyEnum), setClassification(?ClassificationEnum), setUrl(string), setCategories(string ...), setResources(string ...), setComments(string ...), setContacts(string ...), setPriority(?int), setGeo(?float, ?float), setCreated(DateTimeInterface), setLastModified(DateTimeInterface)
AttachmentssetAttachments(Attachment ...), setRelatedTo(Relation ...)
AlarmssetAlarm(bool), setAlarmMinutesBefore(int), setAlarmRepeat(int $count, ?int $intervalMinutes = null), addAlarm(Alarm ...), getAlarms(), hasAlarm()
X-propertiesaddXProperty(string $name, string $value, array $parameters = []), getXProperties()
InvitationssetOrganizer(string $email, ?string $name = null, ?string $sentBy = null, ?string $directory = null, ?string $language = null), addAttendee(Attendee ...), getAttendees(), setMethod(?MethodEnum), setRequestStatuses(RequestStatus ...)
OutputgetICAL(?string $uid = null): string, toIcsFile(?string $uid = null): IcsFile, setFilename(string), addHeader(?Closure $send = null)

setName() and setCalendarType() are kept for compatibility: setProdId() replaces the first, and GREGORIAN is the only calendar type.

Calendar

MethodDescription
addEvent(EventInterface ...), getEvents()The events
addTodo(TodoInterface ...), addJournal(JournalInterface ...), addFreeBusy(FreeBusyInterface ...)The other components, with getTodos(), getJournals(), getFreeBusies()
setProdId(string $organisation, string $product, string $language = 'EN')PRODID of the file
setMethod(?MethodEnum), getMethod()iTIP method of the file
addXProperty(string $name, string $value, array $parameters = [])Non-standard calendar property
getICAL(): string, toIcsFile(): IcsFile, setFilename(string), addHeader(?Closure $send = null)Output

IcalGenerator

Static facade with the default adapters; $clock and $uidGenerator are optional (Clock and UID generator).

MethodReturns
generate(Ical $ical, ?string $uid = null, ?ClockInterface $clock = null, ?UidGeneratorInterface $uidGenerator = null)string, same as $ical->getICAL($uid)
generateCalendar(Calendar $calendar, ?ClockInterface $clock = null, ?UidGeneratorInterface $uidGenerator = null)string, same as $calendar->getICAL()
generateFile(…), generateCalendarFile(…)IcsFile, same arguments
contentType(?MethodEnum $method), contentDisposition(string $filename)The full header lines