Import Calendars, Events From Google Calendar Using PHP.
Problem: how to get Calendar events from Google Calendar.
Requirement:
- Create event in google calander using link https://www.google.com/calendar
- Event should be public so while creating any event set it as public at bottom of page.
- Create new project on Google developer console and enable Google Calender API.
- Set Redirect URIS: http://localhost/google_calendar/calendar.php
- Set Javascript Origing: http://localhost
Solution:
Step 1: Create new folder in your root directory.
E.g: var/www/google_calendar
Then create another folder in this folder
E.g: var/www/google_calender/google-api-php-client
Step 2: Open terminal.
Go in to "google_calendar/google-api-php-client" directory.
E.g: cd /var/www/google_calendar/google-api-php-client
Step 3: Now copy and paste this link into terminal.
git clone https://github.com/google/google-api-php-client.git
Step 4: Now create one php file in "var/www/google_calendar" folder.
E.g: var/www/google_calendar/calendar.php
Step 5: Paste the following code in calender.php file
<?php
require_once 'google-api-php-client/autoload.php';
$client = new Google_Client();
// OAuth2 client ID and secret can be found in the Google Developers Console.
$client->setClientId('YOUR_CLIENT_ID');
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('http://localhost/google_calender/calendar.php');
$client->addScope('https://www.googleapis.com/auth/calendar');
$service = new Google_Service_Calendar($client);
$authUrl = $client->createAuthUrl();
//Request authorization
echo "<a href=$authUrl>Click Here to accept calenders</a>";
echo '<br>';
//$authCode = trim(fgets(STDIN));
$authCode = $_GET['code'];
// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
echo '<br><br><b>Calender list.</b><br>';
$calendarList = $service->calendarList->listCalendarList();
$i=1;
while (true) {
foreach ($calendarList->getItems() as $calendarListEntry) {
echo '<p>'.$i.'=>'.$calendarListEntry->getSummary().'</p>';
$i++;
}
$pageToken = $calendarList->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$calendarList = $service->calendarList->listCalendarList($optParams);
} else {
break;
}
}
echo '<br>';
echo '<b>Event List.</b><br>';
$events = $service->events->listEvents('primary');
$i=1;
while (true) {
foreach ($events->getItems() as $event) {
echo '<p>'.$i.'=>'.$event->getSummary().'</p>';
$i++;
}
$pageToken = $events->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$events = $service->events->listEvents('primary', $optParams);
} else {
break;
}
}
?>
Now run the script.
For more methods of event please check following link.
Comments
Post a Comment