Import an iCalendar (.ics) file to MySQL

Last Updated:

As we know .ICS file format is universal calendar format used to store calendar information within a text file. Lets create a PHP function which will import data from .ICS file and store in MySQL database.

Here we have included a php class file called icalendar.php having class called iCalendar, which will read the ICS file and convert the data to Array format. Once you get the data array you can either save it or you can show it in your webpage in tabular format.
 

import from ics

PHP Code

<?php
include("includes/connection.php");
include("includes/icalendar.php");
$records = mysqli_num_rows(db_query("select * from  events"));
if ($_POST['stage'] == 1) {
    $ical = new iCalendar();
    $filename = $_FILES['file1']['tmp_name'];
    $ical->parse("$filename");
    $ical_data = $ical->get_all_data();

    $timezone = "{$ical_data['VCALENDAR']['X-WR-TIMEZONE']}";
    if (function_exists('date_default_timezone_set'))
        date_default_timezone_set($timezone);

    $strsql1 = "Insert into  events(StartDate,StartTime,EndDate,EndTime,Title,Location,Description) values ";
    if (!empty($ical_data['VEVENT'])) {
        foreach ($ical_data['VEVENT'] as $key => $data) {
		  //get StartDate And StartTime
          $start_dttimearr = explode('T', $data['DTSTART']);
          $StartDate = $start_dttimearr[0];
          $startTime = $start_dttimearr[1];

          //get EndDate And EndTime
          $end_dttimearr = explode('T', $data['DTEND']);
          $EndDate = $end_dttimearr[0];
          $EndTime = $end_dttimearr[1];

          $strsql1.="('".$StartDate."','".$startTime."','".$EndDate."','".$EndTime."','".
		  $connect->real_escape_string($data['SUMMARY']) . "','". 
		  $connect->real_escape_string($data['LOCATION']). "','". 
		  $connect->real_escape_string($data['DESCRIPTION']) . "')";
          $strsql1.=",";
        }
      $strsql1 = rtrim($strsql1, ',');
      db_query($strsql1);
    }
    header('Location:index.php');
}
if ($_GET['stage'] == "empty") {
    db_query(" TRUNCATE events");
    header('Location:index.php');
}
?>

Download File

Total Downloads: 3396
Top