How to insert text with google docs api php How to insert text with google docs api php json json

How to insert text with google docs api php


I believe your situation and goal as follows.

  • You have already been able to use Google Docs API.
  • The script of a copy of a document worked.
  • You want to remove the error in your question.

For this, how about this modification?

From:

$desiredRequests = new Google_Service_Docs_Request(array(    'insertText' => array(    'text' => 'Hello world!',    'location' => array(    'index' => 25))));
  • In your script, when $batchUpdateRequests is retrieved, it becomes as follows.

    {"requests":{"createNamedRangeType":{},"createNamedRangeDataType":{},"createParagraphBulletsType":{},"createParagraphBulletsDataType":{},"deleteContentRangeType":{},"deleteContentRangeDataType":{},"deleteNamedRangeType":{},"deleteNamedRangeDataType":{},"deleteParagraphBulletsType":{},"deleteParagraphBulletsDataType":{},"deletePositionedObjectType":{},"deletePositionedObjectDataType":{},"deleteTableColumnType":{},"deleteTableColumnDataType":{},"deleteTableRowType":{},"deleteTableRowDataType":{},"insertInlineImageType":{},"insertInlineImageDataType":{},"insertTableRowType":{},"insertTableRowDataType":{},"insertTextType":{},"insertTextDataType":{},"replaceAllTextType":{},"replaceAllTextDataType":{},"updateParagraphStyleType":{},"updateParagraphStyleDataType":{},"updateTextStyleType":{},"updateTextStyleDataType":{},"internal_gapi_mappings":{},"modelData":{},"processed":{},"insertText":{}}}
    • I think that this is the reason of your issue.

To:

$desiredRequests = array(new Google_Service_Docs_Request(array(    'insertText' => array(    'text' => 'Hello world!',    'location' => array(    'index' => 25)))));
  • In this modified script, when $batchUpdateRequests is retrieved, it becomes as follows.

    {"requests":[{"insertText":{"text":"Hello world!","location":{"index":25,"segmentId":null}}}]}
    • In this request body, I could confirm that it worked.

Note:

  • If an error like Invalid requests[0].insertText: Index 25 must be less than the end index of the referenced segment occurs, please modify 'index' => 25 to 'index' => 1.

Reference: