File downloads with new version of Google Drive PHP library

Programmers dislike repetitions, I’m no exception of this generic rule. But I like to automate boring and buggy tasks. One of these tasks was to convert the content of three tables which are stored in a Google Docs spreadsheet document. Google offers a nice Google Drive API and lots of documentation and libraries, one of them in my preferred programming language PHP. Thanks to the examples on their documentation pages a first version of a download script was written fast.

But when I tried to combine the vendor libraries with Composer and integrate my code, I ran into problems. The code on the example pages (and in this case my slightly modificated script) didn’t match the current version of the Google API PHP client library.

So I reviewed the differences in the authentication snippet and found a solution. The following snippet is a fully-working example, but only an example to demonstrate the whole process.

To prepare your Google Drive, you have to allow access to your files. You’ll find a description in this answer on Stackoverflow. After preparing your account, please wait some minutes (I didn’t, and wondered why it didn’t work…), because Google has some servers and they need to be informed about the changes.

Because my script runs on console and not as web application, I created a service account which provides a private key file and a service address. These parts and the client email address are needed to access the files (have a look at “example client code”). Another restriction of the example is the uniqueness of the document title. The Drive API allows searching for a document in many ways, but here only the exact title match is implemented. And as you will see, a spreadsheet file is downloaded. Google doesn’t offer downloading tables as CSV, maybe because a single spreadsheet file can have multiple sheets.
I hope the class and client code are self-explaining, and please note again – this is only an example! The differences from the API example are in the getFile() method, Google had refactored the auth and io variables.

At first the composer.json file:

Please see the Composer documentation pages for more information.

The client class with example:

If you have created the necessary files, downloaded the Google API PHP client library with Composer and customized the client part, it should run with php gdrive-example.php.

If you have questions or further information, don’t hesitate to give me your feedback!

Ein Gedanke zu „File downloads with new version of Google Drive PHP library“

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Kategorie: Allgemein