Create Calendar .ICS files with PHP

On a project I was working on recently it would have been cool if we could dynamically create an ICS file so people could download and import events into their calendars.  I did some looking and found several “scripts” that all claimed to do the trick, but none worked quite right.  I kind of pieced them together and came up with this.

 Lets look at a few things.  The header section tells your browser that we’re making an ICS file and it shouldn’t try to display it.  In fact, it should bring up a download dialogue so you can save it to your computer.

The next section sets up the file as a Microsoft Outlook file.  Seems like, without that, there are issues when you go to import it.  Like your calendar needs to know the file is formatted for Outlook.

The biggest section outputs the actual data that shows up in the event.  In my application I put this section in a loop to create the events list.  The $created variable is simply a date.  I used a PHP date function to create the variable.  The rest is pretty well documented.  Oh, and $random_number is really just a random number.  No secret here.

The next section sets up how reminders for the events happen.  You can edit the text as well.

The last section should be left alone.  It’s just closing out the opening tags above.

Not a great explanation of how it works, but you should be able to copy and paste the code and make it work for you.  Hopefully it helps if you need it.

Leave a Reply

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