0
    $client->setAccessToken($_SESSION['access_token']);
    $service = new Google_Service_Docs($client);

    $title = $_SESSION['class'].' - '.date("Y-m-d");
    $document = new Google_Service_Docs_Document(array(
        'title' => $title
    ));

    //everything works until here. For some reason, this line doesn't run. It doesn't even proceed.
    $document = $service->documents->create($document);
    
    //this line isn't even printed
    print_r("success!");

    $documentId = $document->documentId;

    header('Location: https://docs.google.com/document/d/'.$documentId);
    exit();

I've been scratching my head over this for hours. I have no idea why I can't create a new Google Doc. There's absolutely no examples of this online other than from Google and most of the code here is copied straight from them.

This is what I get when I print $document after assigning the title but before executing the service to create a new document.

Google_Service_Docs_Document Object
(
    [bodyType:protected] => Google_Service_Docs_Body
    [bodyDataType:protected] => 
    [documentId] => 
    [documentStyleType:protected] => Google_Service_Docs_DocumentStyle
    [documentStyleDataType:protected] => 
    [footersType:protected] => Google_Service_Docs_Footer
    [footersDataType:protected] => map
    [footnotesType:protected] => Google_Service_Docs_Footnote
    [footnotesDataType:protected] => map
    [headersType:protected] => Google_Service_Docs_Header
    [headersDataType:protected] => map
    [inlineObjectsType:protected] => Google_Service_Docs_InlineObject
    [inlineObjectsDataType:protected] => map
    [listsType:protected] => Google_Service_Docs_DocsList
    [listsDataType:protected] => map
    [namedRangesType:protected] => Google_Service_Docs_NamedRanges
    [namedRangesDataType:protected] => map
    [namedStylesType:protected] => Google_Service_Docs_NamedStyles
    [namedStylesDataType:protected] => 
    [positionedObjectsType:protected] => Google_Service_Docs_PositionedObject
    [positionedObjectsDataType:protected] => map
    [revisionId] => 
    [suggestedDocumentStyleChangesType:protected] => Google_Service_Docs_SuggestedDocumentStyle
    [suggestedDocumentStyleChangesDataType:protected] => map
    [suggestedNamedStylesChangesType:protected] => Google_Service_Docs_SuggestedNamedStyles
    [suggestedNamedStylesChangesDataType:protected] => map
    [suggestionsViewMode] => 
    [title] => Computer 9 - Charity - 2021-01-04
    [internal_gapi_mappings:protected] => Array
        (
        )

    [modelData:protected] => Array
        (
        )

    [processed:protected] => Array
        (
        )

)

1 Answers1

0

PHP Quickstart provides full tutorial on how to read Google Document using Google Docs API.

To create new document, use the example above and replace:

$documentId = '195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE';
$doc = $service->documents->get($documentId);
printf("The document title is: %s\n", $doc->getTitle());

with:

$title = 'My Document';
$document = new Google_Service_Docs_Document(array(
    'title' => $title
));

$document = $service->documents->create($document);
printf("Created document with title: %s\n", $document->title);

Also, Make sure to change the SCOPE of your project to Google_Service_Docs::DOCUMENTS and before running your code, delete the Token.json to restart the process of verification and to create a new token with the scope you've specified.

Your code should look like these:

<?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(Google_Service_Docs::DOCUMENTS);
    $client->setAuthConfig('credentials.json');
    $client->setAccessType('offline');

    // Load previously authorized credentials from a file.
    $credentialsPath = expandHomeDirectory('token.json');
    if (file_exists($credentialsPath)) {
        $accessToken = json_decode(file_get_contents($credentialsPath), true);
    } else {
        // Request authorization from the user.
        $authUrl = $client->createAuthUrl();
        printf("Open the following link in your browser:\n%s\n", $authUrl);
        print 'Enter verification code: ';
        $authCode = trim(fgets(STDIN));

        // Exchange authorization code for an access token.
        $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

        // Store the credentials to disk.
        if (!file_exists(dirname($credentialsPath))) {
            mkdir(dirname($credentialsPath), 0700, true);
        }
        file_put_contents($credentialsPath, json_encode($accessToken));
        printf("Credentials saved to %s\n", $credentialsPath);
    }
    $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);

$title = 'My Document';
$document = new Google_Service_Docs_Document(array(
    'title' => $title
));

$document = $service->documents->create($document);
printf("Created document with title: %s\n", $document->title);

Reference:

DocsScopes

Creating Document

Nikko J.
  • 5,319
  • 1
  • 5
  • 14
  • ```getClient``` requires that the code be run on CLI but my code is already running off of a web server. I did include the documents in my scopes ```$client->addScope("https://www.googleapis.com/auth/documents");```. Aside from the ```getClient()``` difference, why else is my code not working? I know ```$client->setAccessToken($_SESSION['access_token']);``` must work because I've used the same line of code to access the Sheets API and GMail API. So why is Docs suddenly different? – Samuel Chueh Jan 05 '21 at 01:08
  • Do you receive any errors upon executing your code? If yes, could you include it in your post? – Nikko J. Jan 05 '21 at 15:03
  • No errors. Just a blank page. It's so weird. Part of me feels it could be a syntax issue but there's no other documentation out there for Google Docs. – Samuel Chueh Jan 06 '21 at 01:17
  • See [Using OAuth 2.0 for Web Server Applications](https://github.com/googleapis/google-api-php-client) – Nikko J. Jan 06 '21 at 17:40
  • This is the reference I used to set the access token for my client. Works in every other API except Google Docs. – Samuel Chueh Jan 07 '21 at 02:37