Generate .ics files with eluceo/ical
2.xThe eluceo/ical package allows you to generate iCalendar (.ics) files following the RFC 5545 specification. It uses a two-layer architecture to decouple event data from the file format:
- Domain Layer (
Eluceo\iCal\Domain): Use these classes to store calendar information (events, calendars, dates) in simple PHP objects. This layer requires no deep knowledge of the iCalendar specification. - Presentation Layer (
Eluceo\iCal\Presentation): Use these classes to transform your domain objects into the actual iCalendar string representation.
To generate a file, you define your events and calendars using domain entities, then use a CalendarFactory to convert the calendar into a string component.
<?php
use Eluceo\iCal\Domain\Entity\Calendar;
use Eluceo\iCal\Domain\Entity\Event;
use Eluceo\iCal\Domain\ValueObject\Date;
use Eluceo\iCal\Domain\ValueObject\SingleDay;
use Eluceo\iCal\Presentation\Factory\CalendarFactory;
// 1. Create Event domain entity
$event = new Event();
$event
->setSummary('Christmas Eve')
->setOccurrence(
new SingleDay(
new Date(DateTimeImmutable::createFromFormat('Y-m-d', '2030-12-24'))
)
);
// 2. Create Calendar domain entity
$calendar = new Calendar([$event]);
// 3. Transform domain entity into an iCalendar component
$componentFactory = new CalendarFactory();
$calendarComponent = $componentFactory->createCalendar($calendar);
// 4. Set HTTP headers
header('Content-Type: text/calendar; charset=utf-8');
header('Content-Disposition: attachment; filename="cal.ics"');
// 5. Output
echo $calendarComponent;