如何通过使用搜索和替换功能通过API修改Google Docs文档?

问题描述 投票:0回答:1

我需要一个示例,说明如何通过API用Google文档中的现有文本修改现有文档。 documentation仅显示如何插入和删除文本,但不显示如何更新。一直在网上疯狂地寻找示例或指导,但是没有运气。

php google-api google-docs google-docs-api
1个回答
0
投票

最后自己弄清楚了。

首先,请按照this video准备对Google Docs API的身份验证(即使它是关于Google表格的,但过程基本相同)。基本上,它包括以下步骤:

  • Google Developer Console中创建项目
  • 启用Google Docs API
  • 创建凭据,包括用于程序访问的服务帐户
  • 与服务帐户客户的电子邮件地址共享您的文档
  • 安装Google API的PHP客户端:composer require google/apiclient

然后创建如下脚本:

require_once(__DIR__ .'/vendor/autoload.php');
$client = new \Google_Client();
$client->setApplicationName('Some name');  //this name doesn't matter
$client->setScopes([\Google_Service_Docs::DOCUMENTS]);
$client->setAccessType('offline');
$client->setAuthConfig(__DIR__ .'/googleapi-credentials.json');  //see https://www.youtube.com/watch?v=iTZyuszEkxI for how to create this file
$service = new \Google_Service_Docs($client);

$documentId = 'YOUR-DOCUMENT-ID-GOES-HERE';  //set your document ID here, eg. "j4i1m57GDYthXKqlGce9WKs4tpiFvzl1FXKmNRsTAAlH"
$doc = $service->documents->get($documentId);

// Collect all pieces of text (see https://developers.google.com/docs/api/concepts/structure to understand the structure)
$allText = [];
foreach ($doc->body->content as $structuralElement) {
    if ($structuralElement->paragraph) {
        foreach ($structuralElement->paragraph->elements as $paragraphElement) {
            if ($paragraphElement->textRun) {
                $allText[] = $paragraphElement->textRun->content;
            }
        }
    }
}

// Go through and create search/replace requests
$requests = $textsAlreadyDone = $forEasyCompare = [];
foreach ($allText as $currText) {
    if (in_array($currText, $textsAlreadyDone, true)) {
        // If two identical pieces of text are found only search-and-replace it once - no reason to do it multiple times
        continue;
    }

    if (preg_match_all("/(.*?)(dogs)(.*?)/", $currText, $matches, PREG_SET_ORDER)) {
        //NOTE: for simple static text searching you could of course just use strpos()
        // - and then loop on $matches wouldn't be necessary, and str_replace() would be simplified
        $modifiedText = $currText;
        foreach ($matches as $match) {
            $modifiedText = str_replace($match[0], $match[1] .'cats'. $match[3], $modifiedText);
        }

        $forEasyCompare[] = ['old' => $currText, 'new' => $modifiedText];

        $replaceAllTextRequest = [
            'replaceAllText' => [
                'replaceText' => $modifiedText,
                'containsText' => [
                    'text' => $currText,
                    'matchCase' => true,
                ],
            ],
        ];

        $requests[] = new \Google_Service_Docs_Request($replaceAllTextRequest);
    }
    $textsAlreadyDone[] = $currText;
}

// you could dump out $forEasyCompare to see the changes that would be made

$batchUpdateRequest = new \Google_Service_Docs_BatchUpdateDocumentRequest(['requests' => $requests]);
$response = $service->documents->batchUpdate($documentId, $batchUpdateRequest);
© www.soinside.com 2019 - 2024. All rights reserved.