Reputation: 43
I want show the content of a text file stored in a folder on Google Drive. I'm using the Google Drive Api v3. At moment I'm able to show only filename and MimeType but that I need is the content. I want the text file text as string I can't find a suitable function.
This is part of my code so far
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Drive API PHP Quickstart');
$client->setAuthConfig('credentials.json');
$client->setDeveloperKey('$myApiKey'); // API key
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = $myAuthCode;
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Drive($client);
[...]
$file = $service->files->get($fileId);
print "Title: " . $file->getName();
print "Description: " . $file->getDescription();
print "MIME type: " . $file->getMimeType();
Can you help me?
Upvotes: 4
Views: 3405
Reputation: 201693
If my understanding is correct, how about this answer? Please use alt=media
for downloading the file.
$file = $service->files->get($fileId);
print "Title: " . $file->getName();
print "Description: " . $file->getDescription();
print "MIME type: " . $file->getMimeType();
$content = $service->files->get($fileId, array("alt" => "media")); // Added
print $content->getBody(); // Added
$service->files->get($fileId)
downloads the file metadata. So in order to download the file content, please use $service->files->get($fileId, array("alt" => "media"))
.If I misunderstood your question and this was not the direction you want, I apologize.
When you want to use the access token retrieved by OAuth2, please use the following script. In this case, the scope of https://www.googleapis.com/auth/drive.readonly
is used. When you run the script, the URL for retrieving the authorization code is shown in the console. So please put it to your browser and authorize the scope. And input the code of the browser to the console. By this, the access token and refresh token are retrieved and the script works.
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Drive API PHP Quickstart');
$client->setScopes(Google_Service_Drive::DRIVE_READONLY);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token2.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
$client = getClient();
$service = new Google_Service_Drive($client);
$fileId = "###"; // Please set the file ID of the text file on Google Drive.
// Retrieve file metadata.
$file = $service->files->get($fileId);
print "Title: " . $file->getName();
print "Description: " . $file->getDescription();
print "MIME type: " . $file->getMimeType();
// Download file.
$content = $service->files->get($fileId, array("alt" => "media"));
file_put_contents("sample.txt", $content->getBody()); // Please set the filename you want.
When you want to use the API key, please use the following script. In this case, the file is required to be publicly shared. Please be careful this.
Sample script:function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Drive API PHP Quickstart');
$client->setDeveloperKey('###'); // Please set your API key.
return $client;
}
$client = getClient();
$service = new Google_Service_Drive($client);
$fileId = "###"; // Please set the file ID of the text file on Google Drive.
// Retrieve file metadata.
$file = $service->files->get($fileId);
print "Title: " . $file->getName();
print "Description: " . $file->getDescription();
print "MIME type: " . $file->getMimeType();
// Download file.
$content = $service->files->get($fileId, array("alt" => "media"));
file_put_contents("sample.txt", $content->getBody()); // Please set the filename you want.
Upvotes: 3