我们如何使用 google 文档 api 和 PHP 下载 google 文档到我们的本地(计算机)/硬盘?

How we can download a google docs into our local (computer)/hard drive using google docs api with PHP?

我想在使用 google docs api 和 PHP 创建 google PDF 格式的文档到我的本地 computer/hard 驱动器后下载它。 为了创建 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();

为了在我的本地下载这个文件,我浏览了这个 link 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();

文件导出方法是 google 驱动器 api 的一部分,而不是 google 文档 api 的一部分。您需要创建一个驱动服务对象您已经创建了一个文档服务对象。

$service = new Google_Service_Drive($client);

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

文件现在在 $content 中,您只需要将其写入文件即可

file_put_contents($filename, $content);

你的情况,下面的修改怎么样?

1。添加范围以将 Google 文档导出为 PDF 数据。

如果您正在使用以下脚本,

$client->setScopes(Google_Service_Docs::DOCUMENTS);

请修改如下

$client->setScopes(array(Google_Service_Docs::DOCUMENTS,Google_Service_Drive::DRIVE_READONLY));

添加范围时,请删除包含访问令牌和刷新令牌的文件,并请授权范围again.I认为这可能是您问题的原因。

2。创建一个 URL.

在这种情况下,我认为可以将导出的 URL 创建为字符串值,如下所示。

$downloadUrl = "https://docs.google.com/feeds/download/documents/export/Export?exportFormat=pdf&id=" . $documentId;

3。将 Google 文档导出为 PDF 文件。

从您的以下脚本中,

$request = new Google_Http_Request($downloadUrl, 'GET', null, null);
$httpRequest = $service->getClient()->getAuth()->authenticatedRequest($request);

我认为您可能会使用旧版本的 google-api-php-client。当您需要使用旧版本时,我认为通过上述流程,您可以将 Google 文档导出为 PDF 文件。

但是,如果您更新 google-api-php-client,在当前版本中,将使用以下脚本。 Ref

$documentId = "###"; // Please set Document ID. Or when your script is used, please use $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(); // This is data of the exported PDF data.

参考文献: