Friday, April 7, 2017

PHP to prune a Google calendar feed of unwanted events

Here is a little PHP script that I developed to prune unneeded events from a Google calendar feed.

// Set header for calendar and give it a filename
header('Content-type: text/calendar; charset=utf-8');
header('Content-Disposition: attachment; filename=modified_calendar_feed.ics');
 
// Download the calendar feed we need into a variable
$ics = file_get_contents('https://calendar.google.com/calendar/ical/
targetaccountnamehere%40gmail.com/public/basic.ics'); 
// Remove the useless header info (if this is not done, other Google accounts will not be able to add the URL)
preg_match('/PRODID.+?END:VTIMEZONE../s',$ics,$tz);
$ics = str_replace($tz,"",$ics);
 
// Grab the events and dump them into an array
preg_match_all('/BEGIN:VEVENT.+?END:VEVENT../s',$ics,$events);
 
// Step threw the events and remove any that don't contain the keyword/phrase from the feed
foreach ($events[0] as $event) {
if (!stripos($event,"
keyword/phrase the event must have if it is to stay in the feed")) {
$ics = str_replace($event,"",$ics);
}
}
 
// Send the modified calendar feed to the requesting device
echo "$ics";
 
// Destroy the variables before leaving
unset($ics,$events,$event)