How To Import Calendar Events from ICAL .ics File in PHP

Why ICS?

ICS is a global format for calendar files used by several popular calendar and email programs like Google Calendar, Apple iCal, and Microsoft Outlook. .ICS files enable users to share and publish information directly from their calendars over email or by uploading it to the Internet.

The recipients of such files can integrate the calendar dates or events easily into their personal calendars. ICS saves the events and all the other informations of events as plain text files.

Reference : www.online-convert.com/file-format/ics

Import calendar events from iCAl iCS in PHP

In this article, we are going to explain the process of importing events from .ics file. For explanation purpose, we are going to use Google Calendar to create events and to get .ics link of calendar.

Also Read: How to Build REST API Using PHP

Step – 1 : Event creation

Create the events in Google Calendar.we have created sample events Foo and Bar.

Creating Calendar Events

Step – 2 : Getting ICAL .ics link

Go to Calendar Settings -> Calendar Details tab and click on the Green color ICAL button in the Private Address section. The .ics link for current calendar will be available here.

NOTE : Ensure that the calendar is set to share information to public before getting the .ics link

You can make the calendar public by entering into Share this calendar tab and check the option Make this calendar public and save.

Calendar Settings

Getting .ics link:
Getting ICS Links

Step – 3: Copying the iCal link

Once you have copied the iCal link, get all the contents as array. A simple PHP class to do the same is as under:

class ics {
    /* Function is to get all the contents from ics and explode all the datas according to the events and its sections */
    function getIcsEventsAsArray($file) {
        $icalString = file_get_contents ( $file );
        $icsDates = array ();
        /* Explode the ICs Data to get datas as array according to string ‘BEGIN:’ */
        $icsData = explode ( "BEGIN:", $icalString );
        /* Iterating the icsData value to make all the start end dates as sub array */
        foreach ( $icsData as $key => $value ) {
            $icsDatesMeta [$key] = explode ( "\n", $value );
        }
        /* Itearting the Ics Meta Value */
        foreach ( $icsDatesMeta as $key => $value ) {
            foreach ( $value as $subKey => $subValue ) {
                /* to get ics events in proper order */
                $icsDates = $this->getICSDates ( $key, $subKey, $subValue, $icsDates );
            }
        }
        return $icsDates;
    }

    /* funcion is to avaid the elements wich is not having the proper start, end  and summary informations */
    function getICSDates($key, $subKey, $subValue, $icsDates) {
        if ($key != 0 && $subKey == 0) {
            $icsDates [$key] ["BEGIN"] = $subValue;
        } else {
            $subValueArr = explode ( ":", $subValue, 2 );
            if (isset ( $subValueArr [1] )) {
                $icsDates [$key] [$subValueArr [0]] = $subValueArr [1];
            }
        }
        return $icsDates;
    }
}

Here we are utilising the class to get all the datas

/* Replace the URL / file path with the .ics url */
$file = "https://calendar.google.com/sample/ical/sample/basic.ics";
/* Getting events from isc file */
$obj = new ics();
$icsEvents = $obj->getIcsEventsAsArray( $file );

Now, we can get all the events in a array variable called $icsEvents. A simple iteration to print all the events in html table is as under:

/* Here we are getting the timezone to get the event dates according to gio location */
$timeZone = trim ( $icsEvents [1] ['X-WR-TIMEZONE'] );
unset( $icsEvents [1] );
$html = '<table><tr><td> Event </td><td> Start at </td><td> End at </td></tr>';
foreach( $icsEvents as $icsEvent){
        /* Getting start date and time */
        $start = isset( $icsEvent ['DTSTART;VALUE=DATE'] ) ? $icsEvent ['DTSTART;VALUE=DATE'] : $icsEvent ['DTSTART'];
        /* Converting to datetime and apply the timezone to get proper date time */
        $startDt = new DateTime ( $start );
        $startDt->setTimeZone ( new DateTimezone ( $timeZone ) );
        $startDate = $startDt->format ( 'm/d/Y h:i' );
        /* Getting end date with time */
        $end = isset( $icsEvent ['DTEND;VALUE=DATE'] ) ? $icsEvent ['DTEND;VALUE=DATE'] : $icsEvent ['DTEND'];
        $endDt = new DateTime ( $end );
        $endDate = $endDt->format ( 'm/d/Y h:i' );
        /* Getting the name of event */
        $eventName = $icsEvent['SUMMARY'];
        $html .= '<tr><td>'.$eventName.'</td><td>'.$startDate.'</td><td>'.$endDate.'</td></tr>';
}
echo $html.'</table>';

The sample output would be,

Event Outputs

iCal is one of the most popular calendar apps in the Mac ecosystem. However, importing the calendar events from the iCal app is not something that everybody is an expert at.

Hope this guide will help your import calendar events from iCal easily without breaking a sweat.

If you have any more queries, feel free to ask us in comments below.

Realated Posts

3 thoughts on “How To Import Calendar Events from ICAL .ics File in PHP

  1. Andre

    Could I modify the code to accept an ical link that uses parameters? file_get_contents does not accept links with parameters.

    • Sarath Kumar

      Hello Andre,

      Sorry for the delay, file_get_contents() support URL with a parameter for sure, have you tried without https (with HTTP) ?
      or try urlencode() before passing URL as param, and let me know the status of it.

  2. Luke

    Great bro!!!! Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code lang=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" extra="">