Download a Google Doc using the PHP library

At the time of writing this tip, the Zend_Gdata_Docs component of the PHP library does not contain the export/download functionality of the DocList API. Here is an example of using AuthSub and file_get_contents() to download a document as a .txt file:

function download($client, $url, $format=null) {
  $sessionToken = $client->getHttpClient()->getAuthSubToken();
  $opts = array(
    'http' => array(
      'method' => 'GET',
      'header' => "GData-Version: 3.0\r\n".
                  "Authorization: AuthSub token=\"$sessionToken\"\r\n"
  if ($url != null) {
    $url =  $url . "&exportFormat=$format";
  return file_get_contents($url, false, stream_context_create($opts));

// TODO 1: setup a Zend_Gdata_Docs client in $docs_client
// TODO 2: fetch a $feed or $entry
$contentLink = $feed->entries[0]->content->getSrc();
$fileContents = download($docs_client, $contentLink, 'txt');
echo 'Contents of document "' . $feed->entries[0]->title . '":<hr>';
echo "<pre>$fileContents</pre>";


Zach said...

This is exactly what I've been trying to do, but I can't quite get it to work. I keep getting this error:

PHP Fatal error: Call to undefined method Zend_Gdata_HttpClient::getHttpClient()

Do you have any ideas for me?

Eric (Google) said...

Do you have the lastest version of the library? You may also want to run the install checker for a sanity check:


mway said...

This is awesome. Having a minor issue though: when I make the request to the export URL (and after verifying that I can use the same AuthSubToken to query DocumentList via the existing PHP API methods), it just returns the source for the Google login page (eg it looks like Google returned a 301 and redirected because the AuthSubToken was rejected). The AuthSubToken would already have to be scoped for (and I am trying to export a DOC resource), so I'm at a loss as to why the request is failing.

Also, just out of curiosity: when you use Zend_Gdata_ClientLogin::getHttpClient to authenticate manually, and then instantiate an instance of Zend_Gdata_Docs with that client to get the docs client, is it possible to make these requests with that client since there isn't actually an AuthSubToken passed (eg, streamline the process without requiring any redirects)?

Thanks for posting this, btw.


mway said...
This comment has been removed by the author.
Elliot said...

This looks like it is so close to working. Perhaps something has changed with the Gdata API since you wrote this, but I'm running into the following situation.
Creating the Zend_Gdata_Docs client like so:

$oauthOptions = array(
'requestScheme' => Zend_Oauth::REQUEST_SCHEME_HEADER,
'version' => '1.0',
'signatureMethod' => 'HMAC-SHA1',
'consumerKey' => $CONSUMER_KEY,
'consumerSecret' => $CONSUMER_SECRET

$consumer = new Zend_Oauth_Consumer($oauthOptions);
$token = new Zend_Oauth_Token_Access();
$httpClient = $token->getHttpClient($oauthOptions);
$docs = new Zend_Gdata_Docs($httpClient);

Errors when you get to:


Fatal error: Uncaught exception 'Zend_Oauth_Exception' with message 'Method does not exist: getAuthSubToken' in /usr/local/Zend/trunk/library/Zend/Oauth/Client.php:206

Can you give us a short snipped for how you create the Zend_Gdata_Docs client?

Eric (Google) said...

Zend_Oauth_* wasn't around when I wrote this.

Zend_Oauth_Client won't have the getAuthSubToken() method. That's an AuthSub thing. I suspect there's a way to extract the oauth access token as either a method or property from the Zend_OAuth_Consumer or Zend_OAuth_Client, but I'm not familiar with the library.

Ehsan-ul-haq said...


i have checked ocr sample , its extract text from image but it upload result on google doc

i need to display the result in my variable

How ?

any one know



Tim said...

Has anyone had any luck with using ClientLogin?

I've been trying with:


$format = 'xls';

$url = $link;
$authService2 = Zend_Gdata_Docs::AUTH_SERVICE_NAME;
$token = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $authService2)->getClientLoginToken();
$opts = array(
'http' => array(
'method' => 'GET',
'header' => "GData-Version: 3.0\r\n".
"Authorization: GoogleLogin auth=\"$token\"\r\n"
if ($url != null) {
$url = $url . "&exportFormat=$format";
return file_get_contents($url, false, stream_context_create($opts));


but keep getting a 401 unauthorized response


CqN said...

I have tried the code Eric posted, got very close... I can print out the export url for the file I want to download, but after that in the next step it fails as for others here.

Eric, is it possible to use, instead of Auth token as your sample code does, to use simple username, password? Uploading, getting file list, deleting docs from the App store works here with php, using the Zend libarary, with simple username/password. Yes, this may be less secure, but for my purposes password login is sufficient at least for starts.

So if I can kindly show the mods for your script to use user/password, I am eager to try.

BTW, I am using my own domain on the App, so when I try to use the above export url (which needs Auth), from a regular browser just to try, I cannot directly login to the myaccout@mydomain login, since Google login seems to require a @gmail accout...

cambiata said...


I'm also struggling with this..! A working example would be great!

Toby said...

you dont need a gmail account to login to google docs, you just need to register for an account, you can use your normal email address, though personally I would suggest you get a gmail account.

google said...

The Python lib stores both AuthSub (session) and OAuth (access) tokens inside a token_store or within a current_token property, depending on the setup. By default, I believe the token_store is used.

livesexmelbourne strippers

google said...

Penis PumpSydney Escort
I have exactly the same code, but I am getting the following error message: "Fatal error: Call to undefined method

google said...

Several research results have attested that if we eat foods which contain a large quantity of zeaxanthin and lutein, our macula's pigment density can be increased. This means that our retina is better protected,
chat sexLas Vegas Escort

google said...

It encysts in unfavorable surroundings and climatic conditions like, cold, overcrowded places, accumulation of waste products, etc. They transform into a cyst below the temperature of 10°C.

discount sexy lingerieSydney Escort

google said...

This results in weakness, pain and numbness in patients suffering from spinal stenosis. So, what causes spinal stenosis? There is no single reason behind the occurrence of spinal stenosis, but, a multitude of factors that can cause this condition in the body. Let's take a look at them.
Vegas Escortseffects of salvia

google said...

This results in weakness, pain and numbness in patients suffering from spinal stenosis. So, what causes spinal stenosis? There is no single reason behind the occurrence of spinal stenosis, but, a multitude of factors that can cause this condition in the body. Let's take a look at them.
Vegas Escortseffects of salvia

Wonderful Jewelry said...

fashion jewelry wholesale
wholesale fashion jewelry
china jewelry wholesale
china fashion jewelry
jewelry wholesale china
fashion jewelry china
wholesale jewelry
jewelry wholesale

winnieqinjiaxin said...

Once again great post. You seem to have a good understanding of these themes.When I entering your blog,I felt this . Come on and keep writting your blog will be more attractive. To Your Success!
Classic Dresses
Classic Bridesmaid Dresses
trumpet wedding dresses
New Style Flower Girl Dresses
Wedding Dresses with Sleeves

dongsheng said...

Et voici la preuve photographique. Cette sneak peek [ci-dessus] illustre la stratgie d'tre abattu par l'oncle Karl lui-mme, et bien que nous tions secrtement cherche voir miss Dellal apportant ses battues cuirs noirs sur la campagne, shes regardant puissante dame comme porter un gilet blanc et arc dlicate dans leur cheveux tresss.

Thunk Whoda ci.
Mais ne vous inquitez pas, le bord marque Alices continue tre en raison de tact pour saisines de eye-liner noir en plus d'une lvre rouge vif. Le modle est perch sur une table de toilette l'intrieur d'un appartement somptueux haussmannien, tout en prsentant un sac main gris matelass avec la collection Sac Hermès Mini Plume. Nous sommes impatients d'en savoir vraiment ce blog.

Sac Hermès Shoulder Birkin

Tim said...

If you're receiving a 401 unauthorised error, make sure that when you build the auth URL which sends the user to Google to authorise the application that you're requesting a scope string of ''

The examples provided by Google only request scope for, which won't allow you to get a document's content.

ayesha org said...

good help

Welfare Trust

AyuNk Syah said...

WOW! What a great blog to read. Hope you Top 1 Serp publish a lot more blog for other persons to Lingkar Merah discover precisely how beautiful this site is AS Blog i have all new hot car Fortuner SUV Terbaik with high technology 2012. check please. tanks Commonwealth Life Perusahaan Asuransi Jiwa Terbaik Indonesia

world gadget said...

Awesome, Very interesting issue that after a very successful. JR Tutorial Nicely written article good work ! Thanks for the great piece of sharing. Enjoy to read
Commonwealth Life Perusahaan Asuransi Jiwa Terbaik Indonesia
your write .

Andy Gunawan said...

nice share and keep writing

Aelove beL said...

cerita panas
cerita hot
cerita dewasa
cerita hot
cerita cinta
cerita sex
cerita dewasa

Mark said...

Also check this interactive PHP library:

Asep Suryana said...

Hi there. I really appreciate the points you made. I don't think I've actually thought about it in that way. I can really appreciate how you approached the subject matter and what you said really gave me a new perspective. Thanks for taking the time to write this all out.
Your opinion this blog: Hewan Ternak Merawat Burung Kenari Kenari
Ikan Arwana Burung Parkit Obat Hewan Ternak Bebek ayam petelur Cara Ternak Sapi ternak Ayam Belut Ternak Ikan Mas

Cyntia Clara said...

What youre saying is completely true. I know that everybody must say the same thing, but I just think that you put it in a way that everyone can understand. I also love the images you put in here. They fit so well with what youre trying to say. Im sure youll reach so many people with what youve got to say. Aplikasi Game Android Informasi laptop gaming

Terlakushop said...

I have a blog on by alexa values ​​are much smaller, but I wonder why in the Google SERP order actually decreased, why do you think that?
Model baju gamis terbaru
Model baju muslim terbaru cantik
Model tas terbaru wanita
model jilbab terbaru yang lagi trend