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>";

33 comments:

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?
Thanks!

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: http://code.google.com/apis/gdata/articles/php_client_lib.html#installation_checker

Eric

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 docs.google.com (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.

Matt

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

Eric,
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:

$client->getHttpClient()->getAuthSubToken();

with:
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...

hi

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

thanks

Ehsan-ul-haq

Tim said...

Has anyone had any luck with using ClientLogin?

I've been trying with:

[code]

$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));

[/code]

but keep getting a 401 unauthorized response

Thanks!

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...

Hi!

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

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...

Cyst
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 'https://docs.google.com/feeds/ https://docs.googleusercontent.com/ https://spreadsheets.google.com/feeds/'

The examples provided by Google only request scope for http://docs.google.com/feeds/documents, 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
http://promoindonesiaforever.blogspot.com/2012/12/seragam-kerja-kantor-murah-di-surewi.html
http://promoindonesiaforever.blogspot.com/2012/12/baju-seragam-kerja-termurah-hanya-di.html
http://tech-kinodeon.blogspot.com/2012/10/seragam-kerja-kantor-murah-di-surewi.html
http://tech-kinodeon.blogspot.com/2012/11/commonwealth-life-perusahaan-asuransi.html
http://azzalea.blogdetik.com/2012/11/22/rakutencoid-toko-online-murah-serba-ada-barang-unik-jepang/

Aelove beL said...

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

Mark said...

Wonderful.
Also check this interactive PHP library:
http://phplibrary.info

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 blogspot.com 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

mastah jos said...

jika anda bingung apa saja kelebihan phablet di bandingkan tablet dapat langsung membaca pada Alasan Phablet Lebih di Gemari Dari Pada Smartphone dan Tablet yang mana di sana telah menyediakan ulasan lengkap tentang phablet. bagi anda yang sedang mencari cara mengobati penyakit batuk dapat membaca referensinya pada website situsmedis atau dapat langsung membaca pada blog Cara Mengobati Penyakit Batuk Secara Alami, Cepat dan Mudah yang mana anda akan di berikan beberapa cara untuk mengobati penyakit batuk. kulkas panasonic dapat anda lihat pada website kami di hargamesinterbaruku atau bisa mengunjungi penawaran kami pada situs Daftar Harga Kulkas Panasonic Terbaru 2014 yang memberikan banyak sekali penawaran berharga untuk anda. mencari peluang usaha dapat di lakukan di internet seperti mengunjungi situs seribupeluang atau bisa mencoba membaca selengkapnya dengan mengklik Resiko Menjadi Wirausaha Yang Wajib Diketahui yang mana disana tersedia banyak sekali macam-macam peluang usaha baik bagi pemula maupaun bagi seorang pengusaha.

mastah jos said...

This looks like it is so close to working
lihat peluang selengkapnya
klik saja info usaha disini
cari tahu usaha terbaik selengkapnya
baca info usaha sampingan selengkapnya
klik wirausaha disini
info wirausaha selengkapnya
info usaha lebih detail
baca usaha lebih lengkap di sini
read more peluang bisnis
baca artikel bisnis

justen23 said...

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.

digital signature FAQ