0

I'm using the Google API Client Libraries for PHP (Beta) to make changes to a Google Sheet. I would like to access the first worksheet in the spreadsheet and then make changes to it.

$service = new Google_Service_Sheets($this->client);
$spreadsheet = $service->spreadsheets->get($google_sheet_id);
$sheets = $spreadsheet->getSheets();

Using the code above I have an array of Google_Service_Sheets_Sheet objects. If I var_dump() the contents I can see the property I need in the protected array called modelData. I want to access the sheetId property.

...
["modelData":protected]=>
array(3) {
  ["properties"]=>
  array(5) {
    ["sheetId"]=>
    int(123456789)
    ["title"]=>
    string(15) "Page Popularity"
    ["index"]=>
    int(0)
    ["sheetType"]=>
    string(4) "GRID"
    ["gridProperties"]=>
    array(2) {
      ["rowCount"]=>
      int(4)
      ["columnCount"]=>
      int(4)
    }
  }
...

I've tried everything I can think of including the standard PHP magic get/set syntax and nothing works.

$id = $sheets[0]->getSheetId(); // fails
$id = $sheets[0]->sheetId; // fails
$id = $sheets[0]->get('sheetId'); // fails

How do I access properties on this object?

Robbie Lewis
  • 2,844
  • 3
  • 18
  • 29

1 Answers1

0

You might want to check the Reference for Sheets API enter image description here

In the image above, sheets (object) have properties(object) that contains sheetID (what you want to get). To make it short, it looks like this:

Sheets->properties->sheetID

Or:

Sheets:{
    properties:{
         "sheetId": number,
         "title": string,
         "index": number,
         ........
 },
............
}

Try checking the code from this post:

sheet_metadata = service.spreadsheets().get(spreadsheetId=spreadsheet_id).execute()
sheets = sheet_metadata.get('sheets', '')
title = sheets[0].get("properties", {}).get("title", "Sheet1")
sheet_id = sheets[0].get("properties", {}).get("sheetId", 0)

Hope this helps.

Community
  • 1
  • 1
Mr.Rebot
  • 6,703
  • 2
  • 16
  • 91