PHP ICS Parser

repository·main·Indexed 19 days ago

https://github.com/u01jmg3/ics-parser

A PHP library for parsing iCalendar (.ics, .ical, .ifb) files into an associative array model. It supports the expansion of recurring events, time zone handling via IANA, Unicode CLDR, or Windows Time Zones, and provides tools for filtering events by date range to optimize memory usage for large calendars. The library can be initialized from files, strings, or remote URLs with support for HTTP basic authentication.

Tokens
7K
Snippets
23
Records
35
Agent score
66%

What's inside ics-parser

  1. Optimize parsing for large calendars using date ranges

    main

    Because the parser expands (explodes) all recurrence rules into individual event instances, large calendars can consume significant memory. To prevent Fatal error: Allowed memory size exhausted, you can drop events outside a specific window early in the parsing process.

    How to use the fuzzy window optimization:

    1. Identify the range you need (e.g., yesterday, today, and tomorrow).
    2. Set $filterDaysBefore and $filterDaysAfter to a slightly larger window than needed (e.g., +-2d instead of +-1d) to account for imprecise time zone calculations during the early drop phase.
    3. Once parsed, call eventsFromRange() with your precise window (e.g., +-1d) to get the exact events.
  2. Install PHP ICS Parser via Composer

    main

    To install the library, add johngrogg/ics-parser to your composer.json file.

    Note: The Composer package owner is johngrogg, not u01jmg3.

    To use the latest stable v3 branch, use the ^3 version constraint. If you require new features from the development branch, you can require dev-main.

    { "require": { "johngrogg/ics-parser": "^3" } }
  3. Requirements for PHP ICS Parser

    main

    Before installing, ensure your environment meets the following requirements:

    • PHP Version: 5.6.40 or higher.
    • ICS Files: Must be a valid ICS file (.ics, .ical, or .ifb).
    • Time Zone Data: Support for IANA, Unicode CLDR, or Windows Time Zones.
  4. Use the Event API to manage calendar events

    main

    The Event class extends the ICal API and is used to represent individual calendar events. You can instantiate an event with an array of data and use printData() to output the event information within an HTML template.

    // Creating an event with data
    $event = new Event([
        'summary' => 'Meeting',
        'description' => 'Project discussion',
        'start' => '2023-10-27T10:00:00Z'
    ]);
    
    // Printing event data in HTML format
    echo $event->printData();
  5. Use the ICal API to parse data

    main
    The ICal class is the primary interface for parsing iCalendar data. You can initialize it using files, strings, or URLs. Once initialized, you can retrieve calendar metadata (name, description, timezone) and access event data through various filtering methods.
  6. Set a custom User Agent for Outlook compatibility

    main

    Outlook requires a User Agent string to be set in request headers. The parser injects a default User Agent automatically, but you can provide your own using the httpUserAgent argument when instantiating the ICal object.

    $ical = new ICal($url, array('httpUserAgent' => 'A Different User Agent'));
  7. Initialize the ICal parser from a URL

    main

    Use the initUrl method to load iCalendar data from a remote URL. This method supports HTTP basic authentication and various connection options.

    Parameters:

    • $url (required): The URL of the iCal feed.
    • $username (optional): Username for HTTP basic authentication.
    • $password (optional): Password for HTTP basic authentication.
    • $userAgent (optional): Custom User Agent string.
    • $acceptLanguage (optional): The accepted client language.
    • $httpProtocolVersion (optional): The HTTP protocol version.
    • $verifySsl (optional): Boolean to control SSL verification (defaults to true).
    // Example usage of initUrl
    $ical = new ICal();
    $ical->initUrl('https://example.com/calendar.ics', 'user', 'pass', 'MyUserAgent', 'en-US', 'HTTP/1.1', true);
  8. Retrieve events from ICal

    main

    After parsing, you can extract events using several methods depending on your needs:

    • events(): Returns an array of all Event objects.
    • eventsFromRange($rangeStart, $rangeEnd): Returns a sorted array of events within a specific date range. Returns an empty array if no events match.
    • eventsFromInterval($interval): Returns a sorted array of events following a given string/interval.
    • freeBusyEvents(): Returns an array of arrays containing all free/busy event information.
    • hasEvents(): Returns a boolean indicating if the calendar contains any events.
  9. Access calendar metadata

    main

    Use these public methods to retrieve top-level calendar information:

    • calendarName(): Returns the name of the calendar.
    • calendarDescription(): Returns the calendar description.
    • calendarTimeZone($ignoreUtc): Returns the calendar time zone. Use the $ignoreUtc parameter to control behavior.
  10. Instantiate and use the ICal Parser

    main

    The parser converts an iCal file into an associative array model.

    Key Features:

    • Data Structure: Returns an associative array for the calendar and every event.
    • Time Zones: Injects dtstart_tz and dtend_tz keys to provide start and end dates with time zone data applied.
    • DateTime Objects: Uses DateTime objects where possible, though it is limited to relative date formats, which may affect complex recurrence rules (e.g., BYDAY with BYSETPOS).
    • Resolved Arrays: Provides {property}_array keys (e.g., dtstart_array) which contain fully resolved contents of a key/value pair, including timestamps and TZID information.
    // Dump the whole calendar
    var_dump($ical->cal);
    
    // Dump every event
    var_dump($ical->events());
    
    // Dump a parsed event's start date (resolved array)
    var_dump($event->dtstart_array);
  11. Reference the ICal API public methods

    main

    The ICal class provides several public utility methods for handling iCalendar data, including date conversions, validation, and string parsing.

    Date & Time Utilities:

    • iCalDateToUnixTimestamp($icalDate): Returns a Unix timestamp from an iCal date time format.
    • iCalDateWithTimeZone($event, $key, $format = DATE_TIME_FORMAT): Returns a date adapted to the calendar time zone depending on the event TZID.
    • isValidDate($value): Checks if a date string is a valid date.
    • timeZoneStringToDateTimeZone($timeZoneString): Returns a DateTimeZone object based on a string containing a time zone name.

    Event & Data Processing:

    • parseExdates($event): Parses a list of excluded dates to be applied to an Event.
    • sortEventsWithOrder($events, $sortOrder = SORT_ASC): Sorts events based on a given sort order.
    • keyValueFromString($text): Gets the key value pair from an iCal string.