Search code examples
phpicalendar

How to export data in a ics file?


I found this solution for a single event: How to generate .ics file using PHP for a given date range and time but I need to export multiple events in a single file.

I'm not really sure what I should update in the given class, can you please show me some direction in what should be changed?


Solution

  • I really hate the very old PHP code from the link you provide, but try this update:

    <?php
    class ICS {
        var $data = "";
        var $name;
        var $start = "BEGIN:VCALENDAR\nVERSION:2.0\nMETHOD:PUBLISH\n";
        var $end = "END:VCALENDAR\n";
        function ICS($name) {
            $this->name = $name;
        }
        function add($start,$end,$name,$description,$location) {
            $this->data .= "BEGIN:VEVENT\nDTSTART:".date("Ymd\THis\Z",strtotime($start))."\nDTEND:".date("Ymd\THis\Z",strtotime($end))."\nLOCATION:".$location."\nTRANSP: OPAQUE\nSEQUENCE:0\nUID:\nDTSTAMP:".date("Ymd\THis\Z")."\nSUMMARY:".$name."\nDESCRIPTION:".$description."\nPRIORITY:1\nCLASS:PUBLIC\nBEGIN:VALARM\nTRIGGER:-PT10080M\nACTION:DISPLAY\nDESCRIPTION:Reminder\nEND:VALARM\nEND:VEVENT\n";
        }
        function save() {
            file_put_contents($this->name.".ics",$this->getData());
        }
        function show() {
            header("Content-type:text/calendar");
            header('Content-Disposition: attachment; filename="'.$this->name.'.ics"');
            Header('Content-Length: '.strlen($this->getData()));
            Header('Connection: close');
            echo $this->getData();
        }
        function getData() {
            return $this->start . $this->data . $this->end;
        }
    }
    ?>
    

    And use it like that:

    <?php
    $event = new ICS("Test");
    $event->add("2009-11-06 09:00","2009-11-06 21:00","Test Event1","This is an event 1","GU1 1AA");
    $event->add("2010-11-06 09:00","2010-11-06 21:00","Test Event2","This is an event 2","GU1 1AA");
    $event->save(); // $event->show();
    ?>