在一个变量中使用googledrive API v3-php获取googledocs的文件内容



我可以使用驱动器api php获取谷歌文档的文件名,但无法在php变量中获取文件内容。为我提供工作代码,以便在php变量中获取googledoc文件的内容。我查看了api参考页面,但无法理解如何使用代码。php没有给出明确的方法。

<?php
require __DIR__ . '/vendor/autoload.php';

/**
* Returns an authorized API client.
* @return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Drive API PHP Quickstart');
$client->setScopes(Google_Service_Drive::DRIVE_METADATA_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 = '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();
echo '<a href="'.$authUrl.'">Log in here</a>';
//print 'Enter verification code: ';
$authCode = $_GET['code'];
// 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);

$fileId = "1jNCyWDaCq4KrUo3u3HolqQKysv2P5423KErpvHQNjn0";
$file = $service->files->get($fileId);
echo "File name: ".$file->getName();   //Working
echo "MIME type: " . $file->getMimeType(); //Working
$a = $service->files->getContent(); //Not Working provide code
echo "File Content: ".$a;
?>

使用谷歌驱动api获取谷歌文档的内容。

你的问题的答案是你不能。

你需要记住,谷歌驱动器api是一个文件存储api,它可以帮助你上传、下载和列出存储在谷歌驱动器中的文件。它不允许您编辑存储在Google驱动器中的文件。

从谷歌硬盘下载文件到你的硬盘

文件应该在正文中,但这取决于你想要的文件类型。如果是谷歌文档,那么你需要使用文件导出,而不是文件获取。

以下内容应该将谷歌文档导出到microsof-docx文件中,并将其保存到硬盘中。

$file = $service->files->export($fileId, 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', array(
'alt' => 'media' ));
$size = $file->getBody()->getSize();
if($size > 0) {
$content = $file->getBody()->read($size);
}

编辑谷歌驱动器文档的内容

为了编辑谷歌文档的内容,您需要使用谷歌文档api。请记住,googledocapi使您能够以编程方式编辑文档。如果你想在你的网站上很好地显示谷歌文档的内容,你必须自己进行所有的格式化和显示。

最新更新