【问题标题】:How we can download a google docs into our local (computer)/hard drive using google docs api with PHP?我们如何使用带有 PHP 的 google docs api 将 google docs 下载到我们的本地(计算机)/硬盘驱动器中?
【发布时间】: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


    【解决方案1】:

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

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

    如果您使用以下脚本,

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

    请进行如下修改。

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

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

    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,在当前版本中,将使用以下脚本。 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.
    

    参考资料:

    【讨论】:

    • 感谢您的回答,但是当我手动点击 url 时,我可以在本地看到下载的 pdf,但是当我运行 php quickstart.php 时我希望它动态地下载它应该自动将我的文件下载到我的local.But 使用上面的代码我无法验证,因为我只能通过手动点击 url 来验证它。你能告诉我我错过了什么吗?
    • 我正在使用“composer require google/apiclient:^2.12.1”这个版本的库。
    • @Taniya Halder 感谢您的回复。关于but when I just hit the url manually I can see a pdf downloaded in my local but I want it dynamically when I run php quickstart.php it should automatically download my file in my local.,我已经在我的回答中提出了它,比如Please set Document ID. Or when your script is used, please use $documentId = $document-&gt;getdocumentId();。我认为这可能是您期望的结果。对此我深表歉意。
    • 我只是这样做。$documentId = $document->getdocumentId(); $downloadUrl = "docs.google.com/feeds/download/documents/export/…" 。 $documentId; $httpClient = $client->authorize(); $request = new GuzzleHttp\Psr7\Request('GET', $downloadUrl); $response = $httpClient->send($request); $file = $response->getBody();
    • 但它不会自动在我的本地下载该文件。我错过了什么。
    【解决方案2】:

    文件导出方法是 google drive api 的一部分,而不是 google docs 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);
    

    【讨论】:

    • @DalmTo,我完成了你的回答。有了这个我没有收到任何错误,但问题是我看不到本地下载的任何文件我该如何验证。
    • 文件的同意在$content.保存它。使用 file_put_contents。我编辑了我的 anwser。
    • @dalmto,我不想使用 file_put_contents,我想使用 CURL。这个可以吗?
    • 你的代码是 PHP 为什么要切换到 curl? stackoverflow.com/a/1006629/1841839 堆栈上有一堆示例 stackoverflow.com/q/6177661/1841839
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多