Display the contents of a Google Calendar with PHP

About 5 years ago I ran into this page by James Cridland. It’s empty now, but at the time he was sharing a file that parsed Google’s XML feed for a calendar via PHP code. It was particularly useful to me since I work with WordPress, which is written in PHP. On Nov. 17th, 2014, Google deprecated the API that allowed the XML to be parsed in this way, and released a new API. At the time of this writing, James had not made any plans or attempts to replace the old file, and posted a notice that his code no longer worked.

Since I used James’s code for nearly 5 years with excellent results, I’ve decided to share my new version written for Google’s API v3. I have sent this to James and give him free reign to share and modify as he desires, but I thought I’d share it here, just in case he doesn’t want to bother with it anymore.

Some people asked for a way to send donations to thank me for writing and managing this code, so here you go.

This code assumes you know some PHP. It is also written to only display the month and day of an event. Use Google’s page here to find the variables you need if you want to display the time or other features. Just follow the formula I’ve used for the month and day but change the structure of the string to reflect the item you want.

For example here is where I take the full date and set variables to only be the month or the day:

$newmonth = $eventdate->format("M");
$newday = $eventdate->format("j");

If you wanted to show the TIME, you would use:

$newtime = $eventdate->format("h:i");

IMPORTANT STUFF

Note that your calendar must be publicly shared in order to display the events with this code. If your calendar is private, please do NOT use this code.

Screen Shot 2014-11-27 at 2.19.47 PM

Screen_Shot_2014-11-27_at_2_20_05_PM

If your calendar is part of a Google Apps domain you may need to request that sharing be enabled, or change it yourself if you are the admin.

When you create your Public API key in Google developer console make sure you choose a server key.

Screen Shot 2014-11-27 at 2.32.14 PM

To use the script:

  1. Download and install v1 master of Google’s API PHP Client Library here. Drop it into the root of your webserver.
  2. Make a free Google Dev account, enable the google calendar API on your account, and make your calendar project, all here: http://console.developers.google.com/project
  3. Make a PUBLIC API key for your project, and for the API key type, choose SERVER. Leave the IP limitation open for now. You can limit it to your server’s IP if it has a dedicated IP address.
  4. Open the googlesidebar.php file with your code editor of choice.
    1. On line 24 set your application name to your google developer application name.
    2. On line 25 paste the server API key you got from step 3 above.
    3. On line 30 paste the Calendar ID of the calendar you want to share. Sometimes it’s email@gmail.com, sometimes it’s longer.
    4. On line 38 set the number of calendar events you want to display on your website.
  5. Save the file and drop into your webserver anywhere.

Disclaimer: You should really know at least a bit of PHP in order to use this code. Also, I will not support you, so don’t email me to ask for help, I’m not likely to respond. Comments are more likely to get a response by myself or other visitors. If you have problems using the code please make sure you turn on PHP error reports so that you can pinpoint the problem. It’s usually the client library include.

154 Comments
  • Stephen Costello (@stephen_ni)
    Posted at 10:49h, 27 November Reply

    Hi. I’ve tried to get this script working but with no joy. I’m using the correct ID and API key. Any ideas?

    • sbailey1
      Posted at 13:37h, 27 November Reply

      Stephen, I forgot to write that you need to download and drop in the php client library https://developers.google.com/api-client-library/php/ on your server somewhere, and add the include at the top of the page. I’m adding that now so check back in a bit. Thanks for the heads up!

      • abandonedbywolves
        Posted at 18:24h, 28 February Reply

        Thanks for this!!! The documentation google offers is sometimes a little intense, and still confusing to me that they view it as a server key instead of browser, but again, I was chasing the answer to this in all the wrong places. I couldn’t figure out however to access my calendar feed the old fashioned way through a browser either, even with a key, which helps when you’re trying to structure your calendar.

        Also, just a heads up I got the below message when I ran your code by default, looks like they’re changing the path to the autoload:

        Warning: google-api-php-client’s autoloader was moved to src/Google/autoload.php in 1.1.3. This redirect will be removed in 1.2. Please adjust your code to use the new location. in /home/content/c/r/a/craftbrewingco/html/google-api-php-client-master/autoload.php on line 25

        • Sarah Bailey
          Posted at 10:30h, 04 March Reply

          Thanks for the heads up, I’ve corrected this now.

  • James Cridland
    Posted at 16:46h, 30 November Reply

    Delighted to see this. Thanks!

  • dub
    Posted at 11:24h, 01 December Reply

    I used successfully the previous script until November 17, but I can not operate this new one, although having installed the Google API PHP Library and generated my API key. In the meantime I use a jQuery script a few lines :
    var mykey = ‘your_api_key’;
    var calendarid = ‘you_calendar_id’;

    $.ajax({
    type: ‘GET’,
    url: encodeURI(‘https://www.googleapis.com/calendar/v3/calendars/’ + calendarid+ ‘/events?key=’ + mykey),
    dataType: ‘json’,
    success: function (response) {
    //do whatever you want with each
    },
    error: function (response) {
    //tell that an error has occurred
    }
    });

    • sbailey1
      Posted at 11:27h, 01 December Reply

      Dub, rename the google-api-php-client-master folder to be google-api-php-client instead, I removed the master from the include line of the code. Otherwise turn on error reporting and paste here what the error is. 9/10 times it’s something wrong with the include. Wrong location or similar.

      • dub
        Posted at 11:43h, 02 December Reply

        After several errors 400 then 403, after several tries with a Server API key with all IP access allowed, after allowing all referer on a Browser API key, it finally works !
        Thanks a lot ! Now let’s add the schema.org microdata to the extracted events, like it was on my customisation of the previous script !

        • Sarah Bailey
          Posted at 11:50h, 02 December Reply

          I admit I have limited knowledge of schema/microdata, so if you’d like to contribute the microdata code to the project let me know.

  • Mark
    Posted at 11:43h, 01 December Reply

    Hi Thanks. It Works. I used James script before. Is it possible for people who miss event description to add this, as it was in J.C. version?

    • sbailey1
      Posted at 13:10h, 01 December Reply

      Yes just add this around line 60:
      $description = $event->description;
      where $description is the variable you’ll echo in the output.

      • mak
        Posted at 10:31h, 15 December Reply

        this is not displaying the description

        • Sarah Bailey
          Posted at 10:32h, 15 December Reply

          Read up in the comments, you need to add that code yourself.

          • mak
            Posted at 13:24h, 18 December Reply

            Working now! thanks for the tutorial

  • antispe012Larissa
    Posted at 10:18h, 06 December Reply

    it took me 2 weeks to find your script. thank you so much! 🙂 the SERVER api key was the final information needed. google really could add some example code for non-authorized requests.

    • Sarah Bailey
      Posted at 09:15h, 08 December Reply

      So happy I could help! It took me about 8 solid hours to figure out this whole thing via lots of Googling, little of which was found on google itself. So I totally feel your pain! The worst part for me was figuring out how to pass the API key, it wasn’t in any of the examples! I went back later and found it so I think maybe they added it to some of the docs.

  • William
    Posted at 07:48h, 08 December Reply

    Hi! Just installed the scripts. It gives several errors. One says the API is not enabled. Do I have to sign up for the free trial of the Google Cloud Platform? I am a teacher so I use GAFE. Is this not a free service? Do we have to pay after the trial period? Greetings, William.

    • Sarah Bailey
      Posted at 09:16h, 08 December Reply

      William, please read through the comments. No payment or membership required, you need to download the google api php client and place it in your root folder. Again, please read the comments for more details, and I think I commented that in the code as well.

  • Carlos
    Posted at 11:06h, 10 December Reply

    Hi Sarah,

    Thank you so much for this script! I found a minor typo on your code, You have $calendarId on one line and $calendarid on another. This caused a php error when passing the Calendar ID parameter to the Resource.php file.

    Best

    Carlos

    • Sarah Bailey
      Posted at 11:13h, 10 December Reply

      Thanks Carlos! You must have downloaded an older version of the file, the current version doesn’t have that issue. But while I was in there I went ahead and changed the include path to include the “master” part of the folder name since that seems to be an issue for some people, and I added a date to the zip file name so people will know they’re getting the most current version. –Sarah

      • Carlos
        Posted at 14:58h, 10 December Reply

        Got it. Thanks Sarah.

  • Bjarne Kallesø
    Posted at 04:27h, 12 December Reply

    Hi! Thank for for this code. I have used James Cridslands code for some years and now my service does not work. 🙁
    I have tried your code and it works fine, but I also need to add events to my Google Calendars. How di I do this. I need some rights.

    I have found this code from https://developers.google.com/google-apps/calendar/instantiate

    But I can’t get it to work. Can anyone help me in the right direction

    Thanks.
    Best regards
    Bjarne

  • Randy
    Posted at 07:54h, 12 December Reply

    Works great as a base for me. Any clue how to get a map link out of this? I see no evidence of anything like a map link if I do a var_dump. This was in the old API as “where”.

    • Sarah Bailey
      Posted at 08:11h, 12 December Reply

      According to this page https://developers.google.com/google-apps/calendar/migration you should just be able to use $location = $event->location; I don’t know what the output of that is, haven’t tested it, but if it’s not already a map link I would probably look into how to make that into a map link via the new google maps API, shouldn’t be that hard.

      • Randy
        Posted at 12:10h, 12 December Reply

        Awesomeness! Works great. Outputs the exact contents of the location field. Just need to assemble with the proper URL, eg,

        $location = $event->location;
        $maplinkj=”https://maps.google.ch/maps?q=”.urlencode($location);

  • Oliver handschin
    Posted at 09:54h, 12 December Reply

    hello
    ‘ve got a question how can I make the title and details in color. And how do I get the point that I have German names of months ..
    thank you many times for your support
    Gruss Oli

    • Sarah Bailey
      Posted at 10:02h, 12 December Reply

      Oliver, for the colors you just need to use CSS to target the output fields. I’ve already got the classes on there for you. In this case they’re event-container, eventDate, and eventBody. If you need help with CSS try Googling for a tutorial, there are thousands. As far as getting German names the PHP manual says: To format dates in other languages, you should use the setlocale() and strftime() functions instead of date(). So you would need to do some re-coding to make that work.

      • Oliver handschin
        Posted at 10:30h, 12 December Reply

        hello
        Thank you once , now I have this time resolved as :

        summary);

        ++$count; //INCREASE COUNT AND START AGAIN.

        ?>

        description);
        ++$count; //INCREASE COUNT AND START AGAIN.
        ?>

        but I believe that this is so not right now it is not possible to determine the colors there ??
        greeting Oli

        • Sarah Bailey
          Posted at 10:33h, 12 December Reply

          Just add your own classes around the items you want to target if they don’t already have a class.

          • Oliver handschin
            Posted at 12:04h, 12 December Reply

            hello
            I again , now that I have the css manage to but you could help me with the months , this I do not get out because I ‘m not a PHP specialist .
            thank you very much once
            greeting Oli

  • Randy
    Posted at 13:01h, 12 December Reply

    Having a tough time coding to determining if an event is set to private. The reference code for API v3 refers to it, but I’m not hitting the PHP code right… Any ideas? https://developers.google.com/google-apps/calendar/migration.

    • Randy
      Posted at 13:14h, 12 December Reply

      Nevermind… Here it is:

      $private=$event->visibility;
      outputs “private” if private…

      • Sarah Bailey
        Posted at 14:21h, 12 December Reply

        Awesome, glad you figured it out, thanks for posting the solution!

  • Oliver handschin
    Posted at 07:28h, 13 December Reply

    hello
    So I now try the month names in German convert . But somehow this will not work :
    Have the top of the PHP times the Var:

    setlocale ( LC_TIME , ” de_DE “);

    be translated . and
    $newMonth = strftime (“% d% B% Y” , $event date) ;

    instead of :
    $newMonth = $eventdate- > format ( ‘ j F Y “);

    now it does not work, where I have to set this formation .

    Thank you for your help
    greeting Oli

    • Sarah Bailey
      Posted at 07:52h, 13 December Reply

      Check your spaces, there should not be a space in $eventdate. What does echo $newMonth; give you after that line?

    • Sarah Bailey
      Posted at 07:54h, 13 December Reply

      Hard to tell in this font, but make sure there’s no space between strftime and (.

    • Sillo
      Posted at 21:09h, 29 January Reply

      Hey,

      i found a simple solution, how to edit the Month (e.g. in German)

      $newmonth = $eventdate->format("n");//CONVERT REGULAR EVENT DATE TO LEGIBLE MONTH
      $newday = $eventdate->format("d");//CONVERT REGULAR EVENT DATE TO LEGIBLE DAY
      		 
      $newmonth_german = array("Jan","Feb","Mrz","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Dez");
      

      […]

      <span class="month">
      <?php
      
      echo $newmonth_german[$newmonth];
      
      ?>
      </span>
      
      • Sillo
        Posted at 21:19h, 29 January Reply

        hm syntax highlighter seeming broken?

        ok, just format month with: n
        (to get numbers without leading zeros)

        add a array after month format.

        $newmonth_german = array(“Jan”,”Feb”,”Mrz”,”Apr”,”Mai”,”Jun”,”Jul”,”Aug”,”Sep”,”Okt”,”Nov”,”Dez”);

        and edit:

        echo $newmonth;

        to

        echo $newmonth_german[$newmonth];

        • Sarah Bailey
          Posted at 09:48h, 31 January Reply

          Yeah I think there’s a conflict with the syntax plugin, I have been cleaning the comments up when I can, I disabled something so hopefully that’s fixed it.

  • Sarah Bailey
    Posted at 08:14h, 13 December Reply

    Just so everyone is aware, you can post code formatted text by using <code></code> in your comments.

  • mak
    Posted at 09:41h, 15 December Reply

    I have used the script. But its not displaying decription and title of the event. Help me

    • Sarah Bailey
      Posted at 09:55h, 15 December Reply

      Make sure your entire calendar sharing is set to publicly visible.

      • mak
        Posted at 13:25h, 18 December Reply

        That solved the problem. My Calendar sharing was not set to publicly visible. Thanks!!!

  • Joel
    Posted at 11:48h, 15 December Reply

    Thank you for your work and tutorial, Sarah! I am a PHP novice and even worse with Objects, and your work alone helped me sort out my coffeeshop’s Events page. Thanks!

    • Sarah Bailey
      Posted at 11:03h, 04 March Reply

      Glad I could help Joel!

  • cywebit
    Posted at 08:50h, 16 December Reply

    Hi Sarah, I was using ZEND to get events from my google calendars, this API seems much more limited in functionality. Any chance you could help me sort my daily events returned alphabetically? Seems currently, you can’t sort on that or I just haven’t found where/how yet?
    Thanks

    • Sarah Bailey
      Posted at 09:28h, 16 December Reply

      It is definitely limited compared to some alternatives, that’s for sure. Basically the orderby only takes start time and updated. However, you are passing the results into the “events” array so you should be able to sort the array contents and then run the foreach as usual. http://php.net/manual/en/function.sort.php

  • Cywebit
    Posted at 15:17h, 17 December Reply

    Well I’ve not had any luck with PHP sort, perhaps if you have a moment, you could show me an example? I know it’s the way I’m handling the PHP Google API array coming back, that’s where I’, stuck. Thanks

  • Justin
    Posted at 17:33h, 18 December Reply

    This has been a great script, it is greatly appreciated. I have just about everything working, I was just wondering how you may find/sort and publish the last calendar event that occurred before today’s date?

    • Sarah Bailey
      Posted at 17:51h, 18 December Reply

      Thanks Justin!

      On the timeMin line 28 you need something like this

      'timeMin' => strtotime(date(DateTime::ATOM) . ' -1 day'),

      but I haven’t tested it, and this will actually pull all events starting 24 hrs before now, not just the last one published before today. You can also use a similar timeMax to limit the results up to right now:

      'timeMax' => date(DateTime::ATOM),

      but again, haven’t tested this.

      • Justin
        Posted at 14:59h, 19 December Reply

        The last reference worked, but I need to sort the results in a descending order by date so that I can display the last event before today or list events in descending order by start dateTime that occurred before today’s date. I am not sure how to do this correctly. I have everything working pretty close to correctly, I am just having this little problem. I again thank you so much for your time and consideration.

        • Sarah Bailey
          Posted at 15:08h, 19 December Reply

          You need to use rsort() on the events array to reverse the order after you’ve got all the events into it – http://php.net/manual/en/function.rsort.php Google doesn’t let you change the query order so you have to reverse it afterwards.

          • Justin
            Posted at 16:15h, 19 December Reply

            I know I haven’t the knowledge that I should have and appreciate your assistance greatly. I am having some difficulty with this.

            rsort($events->start->dateTime);
            

            Above is what I have placed after the point the events variable is defined. Thank you again for all you have done and are doing.

            • Sarah Bailey
              Posted at 18:24h, 19 December Reply

              1) I was mistaken, I think you actually need usort- http://hk2.php.net/manual/en/function.usort.php Sorry I don’t have time to get into it, I’ve got websites to build and sorting isn’t my forte since I work with WordPress, the query handles that for you.

      • Scott Bestvater
        Posted at 20:11h, 19 December Reply

        I too would like to include all items within the last 24 hours but

        ‘timeMin’ => strtotime(date(DateTime::ATOM) . ‘ -1 day’),

        Does not work…any other suggestions?

        • Scott Bestvater
          Posted at 21:34h, 19 December Reply

          I managed to code this to work now to change it to 1 day earlier – the reason I need that is all day events disappear after 6 pm on that day and I want them to appear throughout the evening:


          //TELL GOOGLE HOW WE WANT THE EVENTS

          $date = new DateTime;
          date_sub($date, date_interval_create_from_date_string('1 day'));

          $params = array(
          'singleEvents' => true, //CAN'T USE TIME MIN WITHOUT THIS, IT SAYS TO TREAT RECURRING EVENTS AS SINGLE EVENTS
          'orderBy' => 'startTime',
          'timeMin' => date_format($date, 'Y-m-d\TH:i:sP'),//ONLY PULL EVENTS STARTING TODAY

          );

  • Jason Daniel
    Posted at 10:02h, 19 December Reply

    This works amazingly well an I thank you for posting it. I have found that I need to load multiple calendars from the same API key, but cannot find a way to do it. I have tried tinkering with the $calendarId=’x@gmail.com’; part but to no avail. I wanted to ask you while I continue to bang on it some more. Thank you.

    • Sarah Bailey
      Posted at 10:04h, 19 December Reply

      Can you give a little more detail? multiple calendars into the same output (one big calendar) or multiple calendars, same API key, different pages, different calendars?

      • Jason Daniel
        Posted at 10:18h, 19 December Reply

        I am looking to read multiple calendar IDs into the same event list, all being under the same API key and on the same page. Since Google Calendar does not support tags or categories, I have had to use different calendars under the same API key.

        • Sarah Bailey
          Posted at 10:30h, 19 December Reply

          OK, see how you define the client variables in the first few lines? You’re going to need to do that for EACH calendar, and then feed them all into the same $events array, and then you’ll probably need to sort them by event date again. It’s not so simple as adding another calendar id on that field.

          • Jason Daniel
            Posted at 16:37h, 19 December Reply

            After a few hours of trial and error, I was able to get it working. Multiple client variables were not needed; only different calenderId variables.

            $client = new Google_Client();
            $client->setApplicationName(&quot;My Calendar&quot;); 
            $client->setDeveloperKey('API key'); 
            $cal = new Google_Service_Calendar($client);
            $calendarId = '111@group.calendar.google.com';
            $calendarId2 = '222@group.calendar.google.com';
            $calendarId3 = '333@group.calendar.google.com';
            $calendarId4 = '444@group.calendar.google.com';
            
            $calendarIdarray = array($calendarId, $calendarId2, $calendarId3, $calendarId4);
            
            $params = array(
            	'singleEvents' => true, 
            	'orderBy' => 'startTime',
            	'timeMin' => date(DateTime::ATOM),
            	);
            
            $countstep = 0;
            
            foreach (range(0,3) as $countstep) {
            $events = $cal->events->listEvents($calendarIdarray[$countstep], $params);
            
            $count = 1; 
            $items_to_show = 4; 
            
            
                foreach ($events->getItems() as $event) { 
            	if($count <= $items_to_show) {
            ...etc etc...
            

            However, I am having a devil of a time getting the array to sort. It is sorting by the CalendarId, when I want it sorted by the date. However, I have been unable to figure out how to extract the date properly that it can be used to sort. I have been scouring the Internet with no result and I have tried different forms of sorting. However, I think it is more to do with not being about to see what to sort by exactly.

            • Sarah Bailey
              Posted at 17:49h, 19 December Reply

              Have you tried a vardump on the $events array to see what options you have?

  • Scott Bestvater
    Posted at 20:05h, 19 December Reply

    Thanks for this! I had been using a modified version of james cridland’s until Google changed their API. I was able to get the old version to work still, although some of my additional features didn’t work. I am working on a slight variation of this code that you can see at http://mes.hsd.ca/newsite/googlesidebar-tips.php. If you have something in the calendar description, “More Info” shows up under the event and when you roll over the more info, the description pops up in the browser. I do need to fix up all the CSS layout and styling, but you can see the functionality.

  • Chris Sanders
    Posted at 22:46h, 29 December Reply

    This post was extremely helpful to me. I’ve been struggling with this for a few weeks. and this is the simplest approach i’ve come across (by far). Thanks!!!

  • Philip Mills
    Posted at 14:43h, 21 January Reply

    Thanks for the script, its a lifesaver after Google changed the API.

    I’m struggling though to understand why the script isn’t showing the correct number of events. I have set it to show 7, and it shows only 4, If i set to 4, it shows 2. Very odd. I’m guessing its something to do with the recurring events being counted as one event only.

    Anyone else have any clues how to get this working correctly?

    • Philip Mills
      Posted at 15:10h, 21 January Reply

      I reverted back to the default script without any mods, and its showing more entries now, so I must have messed something up.
      BUT.
      with an event count of 7, the script shows me 8 events.
      So something is still not right, has anyone else had issues getting it to show the right number of events?

      • Matt
        Posted at 14:21h, 23 March Reply

        Your previous issue is a bit of a mystery, but your latest should be resolved by changing this line:

        if ($count <= $items_to_show)

        to

        if ($count < $items_to_show)

        or setting $count to an initial value of 1.

        Since we’re using a counter here that starts at 0, and counts up to 7 inclusive, you’re going to get 8 results.

  • Display the Contents of a Google Calendar via PHP - SPUNMONKEY DESIGN
    Posted at 14:41h, 02 February Reply

    […] Display Google Calendars with PHP […]

  • Arne
    Posted at 17:56h, 03 February Reply

    Hi Sarah, this tutorial is working so fine. But how in the world can I insert events in a google calender?

  • Max Pier
    Posted at 18:25h, 07 February Reply

    Hi 🙂 thank you so much for this code.
    I got an APIkey and uploaded the PHP library on website, but I got this error… I uncommented the first two debug lines, but It’s all ok with the php script. Seems that the problem is in Curl.php in the PHP library… Don’t know how to solve this. Any idea? 🙂

    Fatal error: Uncaught exception ‘Google_IO_Exception’ with message ‘Failed to connect to 2a00:1450:4016:804::200a: Network is unreachable’ in /srv/disk4/1805325/www/datelsl.me.pn/google-api-php-client/src/Google/IO/Curl.php:109 Stack trace: #0 /srv/disk4/1805325/www/datelsl.me.pn/google-api-php-client/src/Google/IO/Abstract.php(133): Google_IO_Curl->executeRequest(Object(Google_Http_Request)) #1 /srv/disk4/1805325/www/datelsl.me.pn/google-api-php-client/src/Google/Http/REST.php(61): Google_IO_Abstract->makeRequest(Object(Google_Http_Request)) #2 [internal function]: Google_Http_REST::doExecute(Object(Google_Client), Object(Google_Http_Request)) #3 /srv/disk4/1805325/www/datelsl.me.pn/google-api-php-client/src/Google/Task/Runner.php(172): call_user_func_array(Array, Array) #4 /srv/disk4/1805325/www/datelsl.me.pn/google-api-php-client/src/Google/Http/REST.php(47): Google_Task_Runner->run() #5 /srv/disk4/1805325/www/datelsl.me.pn/google-api-php-client/src/Google/Client.php(564): Google_Http_REST::execute(Object(Google_Client in /srv/disk4/1805325/www/datelsl.me.pn/google-api-php-client/src/Google/IO/Curl.php on line 109

    • Sarah Bailey
      Posted at 18:30h, 07 February Reply

      You need to use a custom php.ini file in your web configuration to enable curl. Your host provider can help you if you don’t know how to do that. Just ask them to enable curl in the php config.

      • Max Pier
        Posted at 05:58h, 08 February Reply

        Hi Sarah, thank you. It must be because I’m using a free hosting plan to make some tests… Thanks 🙂

        • Tamer
          Posted at 01:46h, 10 February Reply

          Open:

          Google\IO\Curl.php

          Add to curl options:

          curl_setopt($curl, CURLOPT_SSLVERSION, 1);

  • Viktor
    Posted at 16:53h, 11 February Reply

    Thank you so much for this code! With your help I’ve managed to get some use out of an API for the first time (I’m quite new to this stuff).

    I’ve been able to modify your code to echo location and description with ‘echo $event->location’ and ‘echo $event->description’ but for some reason I can’t echo colorId with ‘echo $event->colorID’. Any idea why this wont work?

    • Sarah Bailey
      Posted at 21:07h, 11 February Reply

      It says here https://developers.google.com/google-apps/calendar/migration that the color is part of a separate resource so you’ll have to look into CalendarListEntry. The calendar color is a user setting for the overall calendar rather than an event, which is what we’re parsing here, so that’s the difference.

      • Viktor
        Posted at 03:06h, 12 February Reply

        Thanks for the quick feedback Sarah 🙂
        I used ‘print_r($event)’ in your code I could see that [colorID] is in fact in the $event but it holds no value.
        I’m probably in way over my head here, but playing around with https://developers.google.com/apis-explorer/#s/calendar/v3/calendar.events.list I realised that the colorId attribute would only be shown if authorized using OAuth 2.0.
        Absolutely not demanding any answers here, just trying to leave a breadcrumb for anyone else trying to figure out the same thing as I am 🙂
        Thanks again Sarah for a great article. It’s been really helpful and educating for me.

  • Merv
    Posted at 14:43h, 12 February Reply

    What a lifesaver. Looking for a couple months to find an alternative to simplePie and Google V2 calendar. Glad I found you.

    A couple of small changes and It works!!
    1. My Google API library is not in the root. Had to modify autoload.php to find the libraries in my php library folder.
    2. I have three (3) calendars and iterate one at a time to display events. Had to put code to only do autoload.php on the first iteration.

    You can see my results with V3 at http://raspberryfalls.org/
    The three calendars displaying events are Raspberry Falls, Around Loudoun and Special Days (Google Holidays).

    Scroll down a bit and check out the Community => Events widget on the right.
    Click on the title to see the description (if not blank). If the first one is blank try the next one.
    Clicking on a “Special Day” takes you to the full calendar.

    You might also notice the capability to add an event to Outlook or personal Google Calendar.

    Thanks again.
    You are a real GEM!!
    Merv

    • Patc
      Posted at 09:14h, 17 April Reply

      Merv,
      I’m trying to do exactly what you’ve done for my community site. Is there any chance that you’d post some of your code to get us going as I’m having difficulty with multiple calendars?
      Any your site looks super.

      thanks
      -pat

      • Merv
        Posted at 08:02h, 18 April Reply

        Hi Pat,
        The site is built on MovableType and I have a Calendar Widget that initiates the Calendar feeds in three steps:

        <!-- Setup width for widget display, constant for all three displays -->
            <mt:Var name="widget_width" value="300px">
        <!-- ***************** Get event schedule feed **************************************** -->
        <!-- Setup parameters for feed display -->
        <!-- Title to show for feed -->
            <mt:Var name="feed_title" value="Raspberry Falls">
        <!-- Set to first feed status -->
            <mt:Var name="desc_id" value="1"> 
        <!-- Pass feed ID -->
            <mt:Var name="feed_id" value="site.admin@raspberryfalls.org"> 
        <!-- Pass how many days to show events for this feed  -->
            <mt:Var name="days" value="+90 days">
        <!-- Go get the calendar data and display in widget (a MovableType Include is like a PHP include() -->
            <mt:Include widget="Calendar feed detail GoogleAPI">
        
        <!-- The following two sets different parameters and then calls the display module -->
        
        <!-- ***************** Get event schedule feed **************************************** -->
        <mt:Var name="feed_title" value="Around Loudoun">
        <mt:Var name="desc_id" value="2">
        <mt:Var name="feed_id" value="4uj41bi03jmv7jl893hlc2fodk@group.calendar.google.com">
        <mt:Var name="days" value="+30 days">
        <mt:Include widget="Calendar feed detail GoogleAPI">
        
        <!-- ***************** Get holiday feed *********************************************** -->
        <mt:Var name="feed_title" value="Special Days">
        <mt:Var name="desc_id" value="3">
        <mt:Var name="feed_id" value="en.usa#holiday@group.v.calendar.google.com">
        <mt:Var name="days" value="+30 days">
        <mt:Include widget="Calendar feed detail GoogleAPI">
        </mt:Unless>
        

        In the called module I only do the Google API autoload() if desc_id = 1.
        I certainly could do all the above in PHP with a loop and parameters stored in an array to be passed to a called PHP subroutine for each iteration in the loop.

        Here’s a link to the code for “Calendar feed detail GoogleAPI” (rather long and involved):
        http://bigsitedemo.com/wp-content/uploads/2015/04/Calendar-feed-detail-GoogleAPI.pdf

        Hope this helps.
        Merv

  • Stephen
    Posted at 23:32h, 19 February Reply

    Hi Sarah,
    This is phenomenal. I’ve reworked a lot of it to get it how I need it, but can’t seem to locate the end date values. I’ve tried $event->end->dateTime; to no avail. How can I grab the end date?

    • Stephen
      Posted at 23:47h, 19 February Reply

      Nevermind. Got it. Not all events have end dates. My code had errored out after the first event because of this.

  • John
    Posted at 14:42h, 26 February Reply

    Thank so much, Sarah. I’ve needed this since Google changed their API. Glad to have learned a few things too!

  • Mainly
    Posted at 10:42h, 02 March Reply

    Wow. First of all, THANK YOU for sharing the source with us. It’s helping me so so much. Now I’m stuck on how to limit the request to the events during just this month. I mean, if I just want the events from the actual month (‘timeMin’ => date(DateTime::ATOM), how would I do that? Thank you so much in advance and share a PayPal link or something!

    • Sarah Bailey
      Posted at 11:06h, 04 March Reply

      Look up at the comment by Scott Bestvater as a starting point for this.

  • pablo esteban segundo guzman labra
    Posted at 10:15h, 04 March Reply

    Hi i thanks 4 all!! well i have this error :s any ones can helpme?
    Deprecated: google-api-php-client’s autoloader was moved to src/Google/autoload.php in 1.1.3. This redirect will be removed in 1.2. Please adjust your code to use the new location. in /var/www/html/virtual/dawchile.cl/www/proyectos/Google-Calendar/autoload.php on line 25 algo

    • Sarah Bailey
      Posted at 10:31h, 04 March Reply

      Download the newest version of the file I just uploaded, this problem is fixed.

  • Pablo Guzman
    Posted at 10:34h, 04 March Reply

    and then i have this other problem
    Fatal error: Uncaught exception ‘Google_IO_Exception’ with message ‘Failed to connect to 2800:3f0:4003:c00::54: Network is unreachable’ in /var/www/html/virtual/dawchile.cl/www/proyectos/copec/intranet/desarrollo/intranet/sistema/api_google/src/Google/IO/Curl.php:110 Stack trace: #0 /var/www/html/virtual/dawchile.cl/www/proyectos/copec/intranet/desarrollo/intranet/sistema/api_google/src/Google/IO/Abstract.php(133): Google_IO_Curl->executeRequest(Object(Google_Http_Request)) #1 /var/www/html/virtual/dawchile.cl/www/proyectos/copec/intranet/desarrollo/intranet/sistema/api_google/src/Google/Auth/OAuth2.php(337): Google_IO_Abstract->makeRequest(Object(Google_Http_Request)) #2 /var/www/html/virtual/dawchile.cl/www/proyectos/copec/intranet/desarrollo/intranet/sistema/api_google/src/Google/Auth/OAuth2.php(309): Google_Auth_OAuth2->refreshTokenRequest(Array) #3 /var/www/html/virtual/dawchile.cl/www/proyectos/copec/intranet/desarrollo/intranet/sistema/api_google/src/Google/Auth/OAuth2.php(234): Google_Auth_OAuth2->refreshTokenWith in /var/www/html/virtual/dawchile.cl/www/proyectos/copec/intranet/desarrollo/intranet/sistema/api_google/src/Google/IO/Curl.php on line 110
    :s i`m dying

    • Sarah Bailey
      Posted at 10:37h, 04 March Reply

      Look in the comments, this has been discussed (by Max Pier).

      • Pablo Guzman
        Posted at 14:35h, 04 March Reply

        Sara u`r awesome!! but, my server already get enable cURL and…. now i almost dead looking a solution :c

  • kevinchamplin
    Posted at 00:45h, 05 March Reply

    How can I add the start and end time (ex: 9:00am – 10:30am)

    • Matt
      Posted at 15:33h, 23 March Reply

      add another parameter:

      $params = array(
      'singleEvents' => true,
      'orderBy' => 'startTime',
      'timeMin' => date(DateTime::ATOM),
      'timeMax' => "2015-03-29T00:00:00Z"
      );

      Full list of available parameters is here:
      https://developers.google.com/google-apps/calendar/v3/reference/events/list

  • Matt
    Posted at 15:35h, 23 March Reply

    If you know that you’re only going to need a finite number of events, I would suggest looking at the ‘maxResults’ parameter value:


    $params = array(
    'singleEvents' => true,
    'orderBy' => 'startTime',
    'timeMin' => date(DateTime::ATOM),
    'maxResults' => 7
    );

    That way you’re not wasting server overhead and memory resources with a gigantic array of events.

    • Sarah Bailey
      Posted at 15:37h, 23 March Reply

      Excellent tip Matt, I’ll add that to the code!

    • Matt
      Posted at 15:37h, 23 March Reply

      By doing this you would not need to use the $count and $items_to_show variables. Of course, the possible downside is that, if you need more events, you will need to send another request for them.

  • Module Agenda - Mirror
    Posted at 07:07h, 03 April Reply

    […] Lien vers le tuto source : http://www.spunmonkey.com/display-contents-google-calendar-php/ […]

  • Sarah Bailey
    Posted at 12:05h, 13 April Reply

    Just uploaded new code to correct an issue where the events were displaying at either UTC or the viewer’s timezone, rather than the calendar. It’s a pretty major fix so make sure you update your code as needed. – Sarah, spunmonkey.com

  • John
    Posted at 08:53h, 14 April Reply

    For some reason, as of a couple of days ago, my module disappeared completely and I get a white screen. I use a module to execute PHP code within itself and display events on my site. I can disable the module to bring my site back but I can’t figure out why it’s changed. When I turn debugging on, I get the message,
    Fatal error: Call to a member function get() on a non-object in /home/(user)/public_html/libraries/legacy/module/helper.php on line 201

    If I open that file, the line that it points to is,
    $paramsChromeStyle = $params->get(‘style’);

    which is located under,
    public static function renderModule($module, $attribs = array())

    Do you have any idea as to what is causing this error?

    • Matt
      Posted at 09:20h, 14 April Reply

      At first glance, it appears to be a config error somewhere in that particular Joomla module or page. I’m not sure why it would randomly pop up. What other changes were you making to the site (if any)? The file that you’re listing is a core part of Joomla. The $params variable should be an instance of the JRegistry class, according to earlier code in that same file. The PHP error seems to state that this variable wasn’t actually able to be instantiated correctly, which shouldn’t happen. I don’t think it’s an error with this code (mine still works)…did you move any files around or delete any files recently that may be part of the Joomla core?

      • John
        Posted at 09:42h, 14 April Reply

        No files modified. It was simply there one day and gone the next. I was using the Flexi Custom Code module to display the PHP code on my site, although it is mixed with HTML also. If I run the code from a PHP file instead of through the module, it shows fine but through the module there are errors.

  • Gary
    Posted at 11:10h, 03 May Reply

    Hi. Great script, just a question as i’m not php guru, if an event is all day it displays as starting 12:00, how can I get either no time or saying ALL DAY? Thanks in advance

  • [php] Manipulate Calendar through Google API | PipisCrew Official Homepage
    Posted at 04:38h, 08 May Reply

    […] Display the contents of a Google Calendar with PHP – http://www.spunmonkey.com/display-contents-google-calendar-php/ Accessing Google Calendar with PHP – […]

  • Sarak Phan
    Posted at 10:03h, 26 May Reply

    Thanks for great tut,
    Yes , I got it work if we shared the calendar to public .but is it possible for nonpublic calendar?

    • Sarah Bailey
      Posted at 10:17h, 26 May Reply

      To use private calendars you’d have to implement Oauth.

      • Sarak Phan
        Posted at 21:29h, 26 May Reply

        Thanks Sarah,

        Do you have any tut of how to implement Oauth?

  • ashanjay99
    Posted at 11:54h, 26 May Reply

    Hello Sarah, thanks for this script. I know you are suppose to make the calendar sharing settings to public. But if its not set to public I get this error on php debug. Any idea how I can detect this in the code and throw a message on client side, if calendar sharing settings are not set correct?


    [26-May-2015 15:44:57 UTC] PHP Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/calendar/v3/calendars/CALID/events?singleEvents=true&orderBy=startTime&timeMin=2015-05-26T15%3A44%3A56%2B00%3A00&maxResults=7&key=KEY: (404) Not Found' in E:\xampp\htdocs\WP\wp-content\plugins\PLUGIN\includes\admin\google\src\Google\Http\REST.php:110
    Stack trace:
    #0 E:\xampp\htdocs\WP\wp-content\plugins\PLUGIN\includes\admin\google\src\Google\Http\REST.php(62): Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request), Object(Google_Client))
    #1 [internal function]: Google_Http_REST::doExecute(Object(Google_Client), Object(Google_Http_Request))
    #2 E:\xampp\htdocs\WP\wp-content\plugins\PLUGIN\includes\admin\google\src\Google\Task\Runner.php(174): call_user_func_array(Array, Array)
    #3 E:\xampp\htdocs\WP\wp-content\plugins\PLUGIN\includes\admin\google\src\Google\Http\R in E:\xampp\htdocs\WP\wp-content\plugins\PLUGIN\includes\admin\google\src\Google\Http\REST.php on line 110

  • Tejas Deshmukh
    Posted at 05:03h, 15 July Reply

    Hello Sarah,

    I am been stuck with calendar invite work for a week, I have tried couple of things which have lead me to partially complete my work. I have posted detailed issue on this link: http://stackoverflow.com/questions/31409300/calendar-event-invitation-for-google-calendar . I would like to know the difference between your approach and the I have code.

    Thanks for your great efforts in posting and maintaining this tutorial.

  • Jesper Christensen
    Posted at 14:33h, 17 July Reply

    Hi

    Thank you for the great tutorial
    This site worked perfectly about a month ago.
    But now it gives a complicated error
    I hope you can help?

    http://sebberklostergolfklub.dk/php/calendar/googlesidebar.php

    Best
    Jesper

    • Sarah Bailey
      Posted at 14:36h, 17 July Reply

      Jesper, looks like something’s up with curl on your website. Have a look at this comment thread http://spunmonkey.com/display-contents-google-calendar-php/#comment-106

      • Nafa
        Posted at 15:20h, 04 August Reply

        Hello,Thank you for the great tutorial. This site worked perfectly about a month ago.
        I have same problem with curl. Curl is enable, curl_setopt($curl, CURLOPT_SSLVERSION, 1); is in curl.php bat on the website is error. Is there any solution?

        Thank

        Frank

        • Jesper Christensen
          Posted at 06:44h, 06 August Reply

          I tried to update with a new version of folder (google-api-php-client-master)
          But now nothing appears on the page
          Please help

      • Jesper Christensen
        Posted at 06:46h, 06 August Reply

        I tried to update with a new version of folder (google-api-php-client-master)
        But now nothing appears on the page

        It seams as if nothing happens after this line
        include ($_SERVER[‘DOCUMENT_ROOT’].’/google-api-php-client-master/src/Google/autoload.php’);

        Please help

  • Kristen
    Posted at 13:29h, 10 September Reply

    OMG… THANK YOU! THANK YOU! THANK YOU!!!

    • Sarah Bailey
      Posted at 13:31h, 10 September Reply

      LOL happy to help 🙂

  • Edward
    Posted at 06:15h, 22 September Reply

    That saved me a LOT of work. Thanks.

  • Helen Cooper
    Posted at 11:35h, 24 September Reply

    Thank you very much Sarah. Our seminar calendar had been down for a while waiting for me to re-write the code, as a non PHP user your work saved me many hours and was quite painless. Big Thumbs Up :o)

  • Helen Cooper
    Posted at 11:45h, 24 September Reply

    I should add that I don’t have root access on our server so just dumped the google-api folder in the same folder as the sidebar.php file and it seemed happy.
    I also pulled over the tweaks from the now redundant version to group by date – a bit hacky but it seems to work ok (not worried about multi-day events I’m afraid!) – I’ve also gone back to using the headings rather than the newer names you had as it meant I didn’t have to redo my css…. All good for an hour or so fiddling.

    Code all here for anyone who might find it useful.

    //SET THE DEFAULT TIMEZONE SO PHP DOESN'T COMPLAIN. SET TO YOUR LOCAL TIME ZONE.
       date_default_timezone_set($calTimeZone);
    	//set the checks for new dates
    	$old_day="";
    	$old_month="";
     //START THE LOOP TO LIST EVENTS
        foreach ($events->getItems() as $event) 
    	 {
     
            //Convert date to month and day
     
             $eventDateStr = $event->start->dateTime;
    			$eventDateStrE = $event->end->dateTime;
             if(empty($eventDateStr))
             {
                 // it's an all day event
                 $eventDateStr = $event->start->date;
    				 $newtime="";
             }
    			else
    			{
    				 $newtime="fill me";
    			}
     
             $temp_timezone = $event->start->timeZone;
    			//THIS OVERRIDES THE CALENDAR TIMEZONE IF THE EVENT HAS A SPECIAL TZ
             if (!empty($temp_timezone)) 
    			{
    				$timezone = new DateTimeZone($temp_timezone); //GET THE TIME ZONE
                     //Set your default timezone in case your events don't have one
    			} 
    			else 
    			{ 
    					$timezone = new DateTimeZone($calTimeZone);
    			}
     
             $eventdate = new DateTime($eventDateStr,$timezone);
    			$eventdateE = new DateTime($eventDateStrE,$timezone);
    			$link = $event->htmlLink;
             $TZlink = $link . "&ctz=" . $calTimeZone; //ADD TZ TO EVENT LINK
    				 							//PREVENTS GOOGLE FROM DISPLAYING EVERYTHING IN GMT
             $newmonth = $eventdate->format("M");//CONVERT REGULAR EVENT DATE TO LEGIBLE MONTH
             $newday = $eventdate->format("j");//CONVERT REGULAR EVENT DATE TO LEGIBLE DAY
    			$newyear = $eventdate->format("Y");//CONVERT REGULAR EVENT DATE TO LEGIBLE DAY
    			
    			
    			if ($newday!=$old_day OR $newmonth!=$old_month) 
    			{ 
    				echo "<br/> <h2>".$newday." ".$newmonth." ".$newyear."</h2>";
    				$old_day=$newday;
    				$old_month=$newmonth;
    			}
    			
    			if($newtime!="")//Are we dealing with a timed event.
    			{
    				 $newtime = $eventdate->format("H:i"); //CONVERT REGULAR EVENT DATE TO LEGIBLE TIME
    				 $endtime = $eventdateE->format("H:i"); //CONVERT REGULAR EVENT DATE TO LEGIBLE TIME
    				 echo "<h3>".$newtime." - ".$endtime." | ";
    			}
    			else{
    				echo "<h3>";
    			}
    			echo $event->summary." | ".$event->location."</h4>";
    	}
    
    • Sarah Bailey
      Posted at 11:47h, 24 September Reply

      Thanks for posting your experience Helen, I’m sure others will find your code useful!

      • Paul
        Posted at 21:24h, 03 November Reply

        Another option, to include multiple calendar feeds, which is the one I’ve adopted, is to build separate multi-dimensional arrays from different calls on the different calendar ids with the fields that interest you, and then multi-sort the relating pile into one date-sorted beauty. Probably many reasons why this is not optimal, but seems to work! Thus:

        $first_events_array = $cal->events->listEvents($calendarId, $params);
        $calTimeZone = $first_events_array->timeZone; //GET THE TZ OF THE CALENDAR
        $second_events_array = $cal->events->listEvents($calendarId1, $params);
        $calTimeZone = $second_events_array->timeZone; //GET THE TZ OF THE CALENDAR

        //SET THE DEFAULT TIMEZONE SO PHP DOESN’T COMPLAIN. SET TO YOUR LOCAL TIME ZONE.
        date_default_timezone_set($calTimeZone);
        $events_master = array();
        foreach ($first_events_array->getItems() as $event) {
        $eventDateStr = $event->start->dateTime;
        $eventdate = new DateTime($eventDateStr,$timezone);
        $title = $event -> summary;
        $location = $event->location;
        $description = $event->description;
        $date = $eventdate->format(‘Y-m-d-G-i’); // this line needed for how I am processing the date later after the array is sorted
        if(!empty($eventDateStr)) // knock out all day events here
        {
        $events_master[]=[
        “title” => $title,
        “location” => $location,
        “description” => $description,
        “date” => $date,
        ];
        }
        }

        foreach ($second_events_array->getItems() as $event) {
        $eventDateStr = $event->start->dateTime;
        $eventdate = new DateTime($eventDateStr,$timezone);
        $title = $event -> summary;
        $location = $event->location;
        $description = $event->description;
        $date = $eventdate->format(‘Y-m-d-G-i’);
        if(!empty($date)) {
        $events_master[]=[
        “title” => $title,
        “location” => $location,
        “description” => $description,
        “date” => $date,
        ];
        }
        }

        //not my function, credit to cagret http://php.net/manual/en/function.array-multisort.php
        function array_msort($array, $cols)
        {
        $colarr = array();
        foreach ($cols as $col => $order) {
        $colarr[$col] = array();
        foreach ($array as $k => $row) { $colarr[$col][‘_’.$k] = strtolower($row[$col]); }
        }
        $eval = ‘array_multisort(‘;
        foreach ($cols as $col => $order) {
        $eval .= ‘$colarr[\”.$col.’\’],’.$order.’,’;
        }
        $eval = substr($eval,0,-1).’);’;
        eval($eval);
        $ret = array();
        foreach ($colarr as $col => $arr) {
        foreach ($arr as $k => $v) {
        $k = substr($k,1);
        if (!isset($ret[$k])) $ret[$k] = $array[$k];
        $ret[$k][$col] = $array[$k][$col];
        }
        }
        return $ret;

        }
        $events=array_msort($events_master, array(‘date’=>SORT_ASC));

    • trishac822
      Posted at 00:49h, 13 December Reply

      I can’t thank you enough for sharing your work! I’ve gotten so far on this tonight because of you. Helen, would you be able to incorporate an example with a second calendar? I’m having difficulties adding it in with any success.

      • trishac822
        Posted at 09:09h, 13 December Reply

        Ah, just spotted Jason Daniel’s post. Thanks so much! It’s looking great!

  • Mike McLoughlin
    Posted at 07:25h, 29 September Reply

    Sarah,

    Thanks for sharing this – and to James for the original inspiration.

    I am trying to achieve something related but slightly different, using a Service Account with domain-wide delegation to view all calendars. This is because the org does not want everyone in the org to view details publicly – just the members of a sub-org which can be controlled via access to the page. It also should enable full access without the need for sharing.

    The service account documentation seems to support this:
    https://developers.google.com/identity/protocols/OAuth2ServiceAccount

    And a Drive example should be adaptable:
    https://developers.google.com/drive/web/delegation#instantiate_a_drive_service_object

    Has anyone had success with this approach?

    – Mike

  • Paul
    Posted at 02:54h, 01 November Reply

    Hi, this looks like it will do what I’m after – but I seem to be falling at the first hurdle – I can’t include autouploader.php; and having explored the google-api folders, it doesn’t seem to be there anywhere… has this been deprecated, or am I just missing something obvious? Any help appreciated!

  • Paul
    Posted at 02:59h, 01 November Reply

    OK – replacing autoupload.php with Client.php seems to have got me somewhere, but now seeing:
    Fatal error: Class ‘GuzzleHttp\Collection’ not found in /Users/paul/Sites/google-api/src/Google/Client.php on line 93

    line 27 of client.php reads: use GuzzleHttp\Client;

    Any ideas?

  • Paul
    Posted at 21:15h, 03 November Reply

    Got it working – thank you so much for this.

  • Grigory Metlenko
    Posted at 06:25h, 27 November Reply

    Thank you, this helped me greatly to fix a WordPress plugin that was still using XML feeds, which have been shut-down by Google

  • parmarsanjaycparmar
    Posted at 05:15h, 17 December Reply

    i have created the calender add task,group using php plz help me

  • Travis Lumpkin
    Posted at 07:30h, 03 January Reply

    Many thanks for your contribution to the community, Sarah. I have found your tutorial very useful in replacing James Cridland’s code. A donation is on the way as thanks! 🙂

    • Sarah Bailey
      Posted at 11:01h, 04 January Reply

      Thanks so much Travis, I’m happy it helped!

  • Rider
    Posted at 12:15h, 27 February Reply

    Greetings Sarah, and thank you so much for this wonderful resource! I’m using it to get a school calendar working (I too used to use GCal XML!), but I need it to not display events that have already passed earlier today. Might you be able to point me in the right direction? I’d sure appreciate it!

    • Sarah Bailey
      Posted at 12:20h, 27 February Reply

      Hi Rider, you need to use strtotime to set the timemin variable to the current time.

      • Rider
        Posted at 19:26h, 28 February Reply

        Thank you Sarah. Just wanted to check with you to make sure I understand, would I use

        ‘timeMin’ => date(DateTime::ATOM, strtotime(‘Now’)),

        in place of

        ‘timeMin’ => date(DateTime::ATOM),

        to get events going forward? 🙂

        Thank you in advance!

        • Sarah Bailey
          Posted at 19:30h, 28 February Reply

          Yep, that should work theoretically.

  • Kim Riemann
    Posted at 13:48h, 16 May Reply

    So this worked out great. I used a bit of the code from Helen to group by dates and from Jason to pull in multiple calendars. I ended up taking the events from multiple calendar and putting them into an associative array, keyed on StartDateTime then ksort to get them in the date order I wanted. Seems to be working. So thanks to you all for your help! Wondering though, has anyone ever done this for private calendars or maybe know of a place I could look for a start? Thanks again!

    • James
      Posted at 05:31h, 12 July Reply

      Hi, Many thanks for this just what I am looking for. May I ask, Kim would you post your code? I am struggling with sorting multiple calendars and cannot get this to work as I hoped.
      Many thanks.

  • Ralf
    Posted at 05:36h, 13 July Reply

    Hi Sarah,

    Thanks for th great tutorial. I have one question though – how one would go about selecting events for a particular day only, just today for example and make sure the events are displayed irrelevant to the time of day (just that the date would be correct)?

  • Devin
    Posted at 22:31h, 20 September Reply

    Is it possible to access an image from the attachment field of a calendar event to display it with the event info? Is there a list of available variables somewhere in Google’s documentation? Thanks for your help! 🙂

  • Devin
    Posted at 15:51h, 21 September Reply

    Thanks Sarah.
    No luck yet getting it to work, even after authorizing OAuth. It seems like the “attachments” property might be an array, so I tried looping through it to get to the fileUrl, with no luck. Any other thoughts or advice would be greatly appreciated. Thanks for your work on this code.

  • Sarah Bailey
    Posted at 15:53h, 21 September Reply

    I would put the “attachments” property into a variable and then do a var_dump to see what it actually is and what the keys are if it’s an array.

  • Devin
    Posted at 16:14h, 21 September Reply

    Thanks! Would seem to be on to something there. This is what it returned:

    array(1) { [0]=> object(Google_Service_Calendar_EventAttachment)#32 (8) { [“fileId”]=> string(28) “0ByMJhaXh1RtjNWRpSm9mTFkyT1E” [“fileUrl”]=> string(79) “https://drive.google.com/file/d/0ByMJhaXh1RtjNWRpSm9mTFkyT1E/view?usp=drive_web” [“iconLink”]=> string(68) “https://ssl.gstatic.com/docs/doclist/images/icon_10_generic_list.png” [“mimeType”]=> NULL [“title”]=> string(18) “test-event-img.jpg” [“internal_gapi_mappings”:protected]=> array(0) { } [“modelData”:protected]=> array(0) { } [“processed”:protected]=> array(0) { } } }

    So it seems “fileURL” is the key I’m looking for.

  • Devin
    Posted at 22:17h, 22 September Reply

    No luck. Google deprecated the ability to host files/images for use on websites via drive. May be something in the drive API…

    Different question: I would like to create a separate event page on my site for each event with more detail. I am able to retrieve the unique event id and pass it via a GET variable in a link. Any idea how I would request a single event from Google calendar using this id?

  • Jacob Jensen
    Posted at 07:56h, 14 December Reply

    Hi Sarah, I get an error when trying to run the script. I’ve read through the comments but can’t find any help there:

    Fatal error: Uncaught exception ‘Exception’ with message ‘This library must be installed via composer or by downloading the full package. See the instructions at https://github.com/google/google-api-php-client#installation.’ in /Applications/MAMP/htdocs/timer/google-api-php-client-master/src/Google/autoload.php:14 Stack trace: #0 /Applications/MAMP/htdocs/timer/googlesidebar.php(17): include() #1 {main} thrown in /Applications/MAMP/htdocs/timer/google-api-php-client-master/src/Google/autoload.php on line 14

    • Sarah Bailey
      Posted at 08:04h, 14 December Reply

      The autoload location has changed. This is the path google gives now – require_once ‘/path/to/google-api-php-client/vendor/autoload.php’;

      • Jacob Jensen
        Posted at 08:55h, 14 December Reply

        I tried that, but when you download it from their GitHub, it doesn’t include a lot of dependencies… after installing it with composer it worked fine… Sorry, asked a bit early in my debugging 🙂

  • Jeff Walloch
    Posted at 14:04h, 21 July Reply

    I built a great web application that was inspired by your post. The code grabbed events from several public calendars for a specific organization and displayed the list on a web page. The user could then page through several days worth of events. It worked great and again I couldn’t have done it without some of the tips and direction from your post.

    I say “worked” since it has stopped working. Suddenly on 7/7/2017 at 11:44pm CDT it stopped working (according to the Google API Manager traffic graph). I thought I would check your post to see if your demo still worked. Well it doesn’t either. It looks like either Google changed something or Google broke something. I have been working on a fix for at least a week now with no success.

    I just thought I would let you know as well as anyone reading this post. If I get a solution or if Google fixes the issue I will post a reply.

    • Sarah Bailey
      Posted at 14:37h, 21 July Reply

      Hi Jeff, thanks for the heads up. The code still works fine where I’m using it in production so I’ll do some digging and try to figure out what’s up. Will report back here if I find anything.

    • Sarah Bailey
      Posted at 16:12h, 21 July Reply

      Hi Jeff, I’ve just looked into my calendar, and it just wasn’t showing any events because I didn’t have any listed. However, do make sure you’re using the v1 version of the google API client because the current version does not work without using composer.

      • Jeff Walloch
        Posted at 17:26h, 21 July Reply

        I was using 1.1.6 since I went live with my application. When it stopped working I tried 2.2.0. It doesn’t work with either. I just tried v1-master like you suggested it still doesn’t work.

        Are you using Composer on your production code? Any chance I could see a sanitized version of your production code? Maybe some line of code there can give me some insight on why it is still working for you?

        I really do appreciate your time helping me work through this.

        • Sarah Bailey
          Posted at 17:38h, 21 July Reply

          No I’m not using composer. Have you checked your PHP version? I’ve only ever used 5.6 with this code and so I know that works. Maybe your host/server updated to 7? The code we use in production is the exact same code provided in the tutorial. Do you get any errors if you turn on error reporting or just a white screen? If you var_dump $events is there anything there? Do some echos in some locations to help you determine where the hangup is.

  • Jeff Walloch
    Posted at 19:24h, 21 July Reply

    I have tried my code on two different hosting accounts. I am doing most of my testing on PHP 5.6.31 so I don’t think it is a PHP problem. I get nothing with error_reporting on. I get nothing when I var_dump the events. I am not sure if I am not connecting correctly with my key or not. I can look at my connection object but I don’t remember what a successful response should be. The script just stops at the listEvents line.

    I posted my problem on stackoverflow with more details and sample code:

    https://stackoverflow.com/questions/45244763/google-calendar-api-bug-or-broken

    • Sarah Bailey
      Posted at 19:32h, 21 July Reply

      Reissue your API key, make sure it’s not limited (at least for now) and double check that the primary calendar on the account is still public.

      • Jeff Walloch
        Posted at 12:55h, 22 July Reply

        Just to give you an update since you have been generous with your time. At this point I have determined that the problem lies with the hosting provider. When I was testing my code I was testing it on 2 different hosting accounts but they were on the same provider. I decided to do some testing on 2 other providers and it was working. I created a support ticket and hopefully they can help me determine what change on their end.

Leave a Reply