Google API How to connect to receive values from spreadsheet

前端 未结 3 885
花落未央
花落未央 2020-12-02 19:17

I embarked on this project thinking it would be simple. Many hours later I\'m realizing the Google API is a bit of a labyrinth with multiple APIs and libraries. I really nee

3条回答
  •  清歌不尽
    2020-12-02 20:12

    I have written a wrapper class for the Google Sheets authentication and sheet cell editing in my recent project. Tested working as of 02 Sep 2015 so it's very up-to-date!

    Prerequisites:

    • Get your Google developer keys etc. ready (This is an excellent and up-to-date article on how to get your API keys etc. - http://konstantinshkut.com/blog/2014/11/01/how_to_get_data_from_google_spreadsheet_in_yii_php_application).
    • Download and install Composer, required for the two necessary libraries google-api-php-client and php-google-spreadsheet-client.
    • Use Composer to install the above two libraries; this is the recommended way to get the libraries working.

    To use the wrapper class:

    // Initialise Google Sheets instance
    $sheets = new GoogleSheets();
    
    $sheets->clientID      = 'YOUR CLIENT ID FROM GOOGLE DEV CONSOLE';
    $sheets->clientEmail   = 'YOUR CLIENT EMAIL FROM GOOGLE DEV CONSOLE';
    $sheets->clientKeyPath = 'PATH TO THE P12 FILE YOU DOWNLOADED FROM GOOGLE DEV CONSOLE';
    $sheets->clientKeyPw   = 'IT IS USUALLY notasecret';
    
    $sheets->appName          = 'WHATEVER NAME YOU WANT';
    $sheets->spreadsheetTitle = 'TITLE FOR THE SPREADSHEET YOU WANT TO EDIT';
    $sheets->worksheetTitle   = 'WORKSHEET TITLE IN THAT SPREADSHEET';
    
    // Authenticate with Google
    $sheets->authenticate();
    
    // Now update the specific row cell
    $sheets->updateListEntry(ROW_HEADER, $submissionID, CELL_HEADER, CELL_VALUE);
    echo "updated!";
    

    And here goes the wrapper class - feel free to modify it - most of the code is pretty much standard, boilerplate code. Tested working!

    // Autoload classes thanks to Composer
    require_once('vendor/autoload.php');
    
    class GoogleSheets {
      // Instance variables
      public $clientID, $clientEmail, $clientKeyPath, $clientKeyPw, $appName, $spreadsheetTitle, $worksheetTitle;
      private $spreadsheetFeed;
    
      // connect to Google using OAuth2, boilerplate code...
      public function authenticate() {
        $obj_client_auth  = new Google_Client ();
        $obj_client_auth -> setApplicationName ($this->appName);
        $obj_client_auth -> setClientId ($this->clientID);
        $obj_client_auth -> setAssertionCredentials (new Google_Auth_AssertionCredentials (
            $this->clientEmail, 
            array('https://spreadsheets.google.com/feeds','https://docs.google.com/feeds'), 
            file_get_contents ($this->clientKeyPath), 
            $this->clientKeyPw
        ));
        $obj_client_auth -> getAuth () -> refreshTokenWithAssertion ();
        $obj_token  = json_decode ($obj_client_auth -> getAccessToken ());
        $accessToken = $obj_token->access_token;
    
        $serviceRequest = new Google\Spreadsheet\DefaultServiceRequest($accessToken);
        Google\Spreadsheet\ServiceRequestFactory::setInstance($serviceRequest);
        $spreadsheetService = new Google\Spreadsheet\SpreadsheetService();
        $this->spreadsheetFeed = $spreadsheetService->getSpreadsheets();
    }
    
    // Find matching row with header $field and cell value $value, and update cell with header $cellHeader to $cellValue
    public function updateListEntry($field, $value, $cellHeader, $cellValue) {
        // Get the required spreadsheet, then worksheet by title
        $spreadsheet = $this->spreadsheetFeed->getByTitle($this->spreadsheetTitle);
        $worksheetFeed = $spreadsheet->getWorksheets();
        $worksheet = $worksheetFeed->getByTitle($this->worksheetTitle);
    
        // sq stands for structured query
        $listFeed = $worksheet->getListFeed(array("sq" => $field . " = " . $value));
        $entries = $listFeed->getEntries();
        $listEntry = $entries[0];
    
        $values = $listEntry->getValues();
        $values[$cellHeader] = $cellValue;
        $listEntry->update($values);
    }
    

    }

提交回复
热议问题