繁体   English   中英

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

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

在使用谷歌文档 api 和 PHP 创建谷歌文档后,我想在我的本地计算机/硬盘驱动器中下载 PDF 格式的谷歌文档。为了创建谷歌文档,我正在使用下面的代码,从那里我可以获取我想要下载的文档 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();

文件导出方法是 google drive api 的一部分,不是 google docs api。你需要创建一个 drive service object 你已经创建了一个 docs service object。

$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、增加一个scope,用于导出Google Document为PDF数据。

如果您使用以下脚本,

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

请修改如下。

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

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

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 Document 导出为 PDF 文件。

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

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

参考:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM