Skip to content
Snippets Groups Projects

iCal to JSON (for FullCalendar)

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by Anton Sarukhanov
    Edited
    ical-to-json-shitty.php 2.15 KiB
    <?php
    /* 
        Output a JSON array that can be consumed by FullCalendar (fullcalendar.io).
        
        This uses code.google.com/p/ics-parser which is problematic because it doesn't handle recurring events.
        
        TODO: Rewrite it to use github.com/johngrogg/ics-parser as that seems to support recurring events and more.
    */
    
    // Include the iCal Reader library
    require_once('lib/ics-parser.php');
    // Change this to use iCalReader instead!
    //require_once('lib/class.iCalReader.php');
    
    // Initialize the iCal Reader
    $ical   = new ICal('https://calendar.example.com/path/to/your/calendar.ics');
    
    // Get Unix timestamps for 12:00AM today, and 12:00AM tomorrow.
    $beginningOfToday = mktime( 0, 0, 0, date("n"), date("j"), date("Y") );
    $beginningOfTomorrow = $beginningOfToday + 86400;
    
    // Use those to define a time range for the iCal library, and get the events
    $events = $ical->eventsFromRange($beginningOfToday, $beginningOfTomorrow);
    
    
    // We only need some information from each event
    // Create an empty array to store our "processed" versions.
    $out = array();
    
    // Loop thru events from the iCal reader
    foreach ($events as $event) {
    
        // Convert the start and end times to Unix timestamps
        $start = strtotime($event['DTSTART']);
        $end = strtotime($event['DTEND']);
        
        // Determine if its an "All-Day" event
        if ($end - $start == 86400) $allday = true;
        else $allday = false;
        
        // This is hacky. If we use a public iCal feed from Zimbra, it won't
        // contain any private events at all. I *want* to display the private
        // events, so people see that I'm busy, but I don't want to display
        // the event details. So I use a private iCal and replace the name
        // of any events flagged as "PRIVATE" with "Private Event".
        if ($event['CLASS'] !== "PUBLIC") $event['SUMMARY'] = "Private Event";
    
        // Put the collected data into our "out" array.
        $out[] = array(
            "title" => $event['SUMMARY'],
            "allDay" => $allday,
            "start" => $start,
            "end" => $end,
        );
    }
    
    // Send a JSON header to comply with HTTP protocol.
    header("Content-type: application/json");
    
    // Convert the "out" array into a JSON string and send it.
    echo json_encode($out);
    ?>
    0% Loading or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Finish editing this message first!
    Please register or to comment