【发布时间】:2022-02-17 16:14:13
【问题描述】:
在使用带有 PHP 的 google docs api 创建它后,我想在我的本地计算机/硬盘驱动器中下载 PDF 格式的 google 文档。 为了创建谷歌文档,我使用下面的代码,我可以从中获取我想要下载的文档 ID。
$service = new Google_Service_Docs($client);
$title = 'Demo document';
$document = new Google_Service_Docs_Document([
"title" => "Test1",
]);
$document = $service->documents->create($document);
$documentId = $document->getdocumentId();
为了在我的本地下载这个文件,我浏览了这个链接 https://developers.google.com/drive/api/v2/reference/files/get?apix_params=%7B%22fileId%22%3A%221v3DlRiUGic0oUFg3vJmKkZ2PyyG-PJTn0J2nftVtBfo%22%7D#examples 的文档,我正在使用这个代码 -
$file = $service->files->get($documentId);
$downloadUrl = $file->getDownloadUrl();
if ($downloadUrl) {
$request = new Google_Http_Request($downloadUrl, 'GET', null, null);
$httpRequest = $service->getClient()->getAuth()->authenticatedRequest($request);
if ($httpRequest->getResponseHttpCode() == 200) {
return $httpRequest->getResponseBody();
} else {
// An error occurred.
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
但我收到此错误 -
PHP Notice: Undefined property: Google\Service\Docs::$files in
PHP Fatal error: Uncaught Error: Call to a member function export() on null
任何人都可以帮助我解决我所犯的错误以及我必须做些什么来实现这一目标。
我也试过这样,但它也给我同样的错误-
$file = $service->files->export($documentId, 'application/pdf', array(
'alt' => 'media' ));
$size = $file->getBody()->getSize();
if($size > 0) {
$content = $file->getBody()->read($size);
}
编辑的代码 -
<?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 Docs API PHP Quickstart');
$client->setScopes([
"https://www.googleapis.com/auth/documents",
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/drive",
Google_Service_Drive::DRIVE_READONLY,
]);
// $client->setScopes(Google_Service_Drive::DRIVE);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory('token.json');
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} else {
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
if (!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
}
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
/**
* Expands the home directory alias '~' to the full path.
* @param string $path the path to expand.
* @return string the expanded path.
*/
function expandHomeDirectory($path)
{
$homeDirectory = getenv('HOME');
if (empty($homeDirectory)) {
$homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
}
return str_replace('~', realpath($homeDirectory), $path);
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Docs($client);
$driveService = new Google_Service_Drive($client);
$title = 'Demo document';
$document = new Google_Service_Docs_Document([
"title" => "Test1",
]);
$document = $service->documents->create($document);
$documentId = $document->getdocumentId();
$requests = [];
$index = 1;
$requests = [
new Google_Service_Docs_Request([
'insertTable' => [
'location' => ['index' => $index],
'columns' => 2,
'rows' => 2
]
]),
];
$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest([
'requests' => $requests
]);
$result = $service->documents->batchUpdate($documentId, $batchUpdateRequest);
$documentId = $document->getdocumentId();
$downloadUrl = "https://docs.google.com/feeds/download/documents/export/Export?exportFormat=pdf&id=" . $documentId;
$httpClient = $client->authorize();
$request = new GuzzleHttp\Psr7\Request('GET', $downloadUrl);
$response = $httpClient->send($request);
$file = $response->getBody();
【问题讨论】:
标签: php google-api google-drive-api google-api-php-client google-docs-api