google spreadsheet api php

PHP Quickstart

Complete the steps described in the rest of this page to create a simple PHP command-line application that makes requests to the Google Sheets API.

Prerequisites

To run this quickstart, you need the following prerequisites:

Step 1: Install the Google Client Library

See the library’s installation page for the alternative installation options.

Step 2: Set up the sample

Create a file named quickstart.php in your working directory and copy in the following code:

Step 3: Run the sample

Run the sample using the following command:

The first time you run the sample, it prompts you to authorize access:

Browse to the provided URL in your web browser.

If you are not already signed in to your Google account, you are be prompted to sign in. If you are signed in to multiple Google accounts, you are asked to select one account to use for the authorization.

Notes

Troubleshooting

This section describes some common issues that you may encounter while attempting to run this quickstart and suggests possible solutions.

SSL certificate problem: unable to get local issuer certificate

This error indicates that the underlying HTTP libraries can’t find a certificate store, and are therefore unable to setup the SSL connection to Google’s servers. See the Guzzle library’s documentation for information on how to setup a certificate store on your machine.

Uncaught InvalidArgumentException: missing the required redirect URI

This error occurs when the credentials.json file used contains a client ID of the wrong type. This code requires an OAuth client ID of type Other, which will be created for you when using the button in Step 1. If creating your own client ID please ensure you select the correct type.

This app isn’t verified

If the OAuth consent screen displays the warning «This app isn’t verified,» your app is requesting scopes that provide access to sensitive user data. If your application uses sensitive scopes, your your app must go through the verification process to remove that warning and other limitations. During the development phase you can continue past this warning by clicking Advanced > Go to (unsafe).

Further reading

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Источник

[Примеры] Google Sheets/Таблицы API PHP

Содержание:

codd.mail@gmail.com или в telegram alex_codd

1. Подготовительный этап

1. Создаём сервисный аккаунт и получаем ключ доступа к API.
2. Открываем доступ к таблице для email адреса сервисного аккаунта:

google spreadsheet api php. Смотреть фото google spreadsheet api php. Смотреть картинку google spreadsheet api php. Картинка про google spreadsheet api php. Фото google spreadsheet api php

Email адрес сервисного аккаунта можно узнать на странице вашего проекта в Google Developers Console:

google spreadsheet api php. Смотреть фото google spreadsheet api php. Смотреть картинку google spreadsheet api php. Картинка про google spreadsheet api php. Фото google spreadsheet api php

3. Устанавливаем библиотеку для работы с Google APIs: Google APIs Client Library for PHP.
Для установки с помощью Composer выполните в консоли следующие команды:

google spreadsheet api php. Смотреть фото google spreadsheet api php. Смотреть картинку google spreadsheet api php. Картинка про google spreadsheet api php. Фото google spreadsheet api php

После установки подключаем файл AutoLoader:

4. Ключ сервисного аккаунта, созданный на первом шаге, кладём в папку с нашим проектом.

google spreadsheet api php. Смотреть фото google spreadsheet api php. Смотреть картинку google spreadsheet api php. Картинка про google spreadsheet api php. Фото google spreadsheet api php

2. Приступаем к работе с API Google Sheets

google spreadsheet api php. Смотреть фото google spreadsheet api php. Смотреть картинку google spreadsheet api php. Картинка про google spreadsheet api php. Фото google spreadsheet api php

spreadsheetId — ID таблицы (example blog)
sheetId — ID листа (Лист 1, Лист 2, …)

Источник

Google spreadsheet api php

This library is no longer maintained. Please use the official Google PHP Client

This library provides a simple interface to the Google Spreadsheet API v3.

There are a couple of important things to note.

I strongly recommend you read through the official Google Spreadsheet API documentation to get a grasp of the concepts.

Using Composer is the recommended way to install it.

The first thing you will need to do is initialize the service request factory:

Note: For Windows users, you can disable the ssl verification by ‘$serviceRequest->setSslVerifyPeer(false)’

Retrieving a list of spreadsheets

Once you have a SpreadsheetFeed you can iterate over the spreadsheets using a foreach loop by calling the ‘getEntries()’ method or you can retrieve a single spreadsheet by it’s title.

Note: The ‘getByTitle’ method will return the first spreadsheet found with that title if you have more than one spreadsheet with the same name.

Retrieving a public spreadsheet

A public spreadsheet is one that has been «published to the web». This does not require authentication. e.g.

The spreadsheet id can be copied from the url of the actual spreadsheet in Google Drive.

Retrieving a list of worksheets

You can retrieve a list of worksheets from a spreadsheet by calling the getWorksheets() method.

You can loop over each worksheet using ‘getEntries()’ or retrieve a single worksheet by it’s title.

Adding a worksheet

To create a new worksheet simply use the ‘addWorksheet()’ method. This takes 3 arguments:

Adding headers to a new worksheet

The Google Spreadsheet API does not allow you to update a list row if headers are not already assigned. So, when you create a new worksheet, before you can add data to a worksheet using the ‘Adding/Updating a list row’ methods above, you need to add headers.

To add headers to a worksheet, use the following:

The only required parameter is the worksheet name, The row and column count are optional. The default value for rows is 100 and columns is 10.

Deleting a worksheet

It’s also possible to delete a worksheet.

List feeds work at the row level. Each entry will contain the data for a specific row.

Note: You can not use formulas with the list feed. If you want to use formulas then you must use the cell feed (described below).

Retrieving a list feed

Once you have a list feed you can loop over each entry.

The getValues() method returns an associative array where the keys are the column names and the values are the cell content.

Note: The Google api converts the column headers to lower case so the column headings might not appear to be the same as what you see in Google Drive using your browser.

Note: If there is data for a particular row which does not have a column header then Google randomly generates a header and as far as I know it always begins with an underscore. Bear in mind that this is not generated by this library.

You can also sort and filter the data so you only retrieve what is required, this is expecially useful for large worksheets.

When adding or updating a row the column headers need to match exactly what was returned by the Google API, not what you see in Google Drive.

Updating a list row

Cell feed deals with individual cells. A cell feed is a collection of cells (of type CellEntry)

Retrieving a cell feed

You can retrieve a single cell from the cell feed if you know the row and column numbers for that specific cell.

You can then update the cell value using the ‘update’ method. The value can be a primitive value or a formula e.g.

Updating multiple cells with a batch request

When attempting to insert data into multiple cells then consider using the batch request functionality to improve performance.

To use the batch request functionality you need access to a cell feed first. You can not use batch requests with list feeds.

About

A PHP library for accessing and manipulating Google Spreadsheets

Источник

How do I access the Google Spreadsheets API in PHP?

So, it seems like everyone’s passing the buck. I just need to write some PHP code that requests and processes data from a Google Spreadsheet. How do I do that? Please don’t link me to similar posts or pages without checking to be sure that they are 100% up to date, I’ve been sifting through a huge mess of posts for hours that are all full of outdated and deprecated dependencies.

3 Answers 3

You’ll need to use the Google APIs Client Library for PHP as well to authenticate via OAuth2. Developer documentation is linked on the github page.

Thanks for the hints and links on this page, I wanted to share what I ended up doing to read a google spreadsheet in php. You can access the spreadsheet in json format, and don’t need to use api or zend framework or gdata library. PhP can handle json very easily and it was the most neat solution I could reach to because it has no dependency to any third party libraries.

Here is a sample link for getting a spreadsheet in json format.

Please note if spreadsheet is private you still need to follow the authentication steps to get token to access to the page. In my case the spreadsheet was public.

Also you can access the spreadsheet via feed list or cell based (replace the list in the url with cell)

You can try the link in a browser and see the json result.

google spreadsheet api php. Смотреть фото google spreadsheet api php. Смотреть картинку google spreadsheet api php. Картинка про google spreadsheet api php. Фото google spreadsheet api php

(Aug 2016)

As of this past May, you now have a better solution.

No more passing the buck:

Note the Sheets API allows you to create spreadsheets & sheets, upload & download data, as well as, in the general sense, programmatically access a Sheet as if you were using the user interface (create frozen rows, perform cell formatting, resizing rows/columns, adding pivot tables, creating charts, etc.), but to perform file-level access such as uploads & downloads, imports & exports (same as uploads & downloads but conversion to/from Google Apps formats), you would use the Google Drive API instead.

Источник

REST Resource: spreadsheets

Resource: Spreadsheet

Resource that represents a spreadsheet.

JSON representation

The ID of the spreadsheet. This field is read-only.

Overall properties of a spreadsheet.

The sheets that are part of a spreadsheet.

The named ranges defined in a spreadsheet.

The url of the spreadsheet. This field is read-only.

The developer metadata associated with a spreadsheet.

A list of external data sources connected with the spreadsheet.

Output only. A list of data source refresh schedules.

SpreadsheetProperties

Properties of a spreadsheet.

Fields
spreadsheetId
JSON representation

The title of the spreadsheet.

The locale of the spreadsheet in one of the following formats:

an ISO 639-1 language code such as en

a combination of the ISO language code and country code, such as en_US

Note: when updating this field, not all locales/languages are supported.

The amount of time to wait before volatile functions are recalculated.

The default format of all cells in the spreadsheet. CellData.effectiveFormat will not be set if the cell’s format is equal to this default format. This field is read-only.

Determines whether and how circular references are resolved with iterative calculation. Absence of this field means that circular references result in calculation errors.

Theme applied to the spreadsheet.

RecalculationInterval

An enumeration of the possible recalculation interval options.

Fields
title
Enums
RECALCULATION_INTERVAL_UNSPECIFIEDDefault value. This value must not be used.
ON_CHANGEVolatile functions are updated on every change.
MINUTEVolatile functions are updated on every change and every minute.
HOURVolatile functions are updated on every change and hourly.

IterativeCalculationSettings

Settings to control how circular dependencies are resolved with iterative calculation.

JSON representation

When iterative calculation is enabled, the maximum number of calculation rounds to perform.

When iterative calculation is enabled and successive results differ by less than this threshold value, the calculation rounds stop.

SpreadsheetTheme

Represents spreadsheet theme

Fields
maxIterations
JSON representation

Name of the primary font family.

The spreadsheet theme color pairs. To update you must provide all theme color pairs.

ThemeColorPair

A pair mapping a spreadsheet theme color type to the concrete color it represents.

Fields
primaryFontFamily
JSON representation

The type of the spreadsheet theme color.

The concrete color corresponding to the theme color type.

NamedRange

Fields
colorType
JSON representation

The ID of the named range.

The name of the named range.

The range this represents.

DataSource

Information about an external data source in the spreadsheet.

Fields
namedRangeId
JSON representation

The spreadsheet-scoped unique ID that identifies the data source. Example: 1080547365.

The DataSourceSpec for the data source connected with this spreadsheet.

All calculated columns in the data source.

The ID of the Sheet connected with the data source. The field cannot be changed once set.

When creating a data source, an associated DATA_SOURCE sheet is also created, if the field is not specified, the ID of the created sheet will be randomly generated.

DataSourceSpec

This specifies the details of the data source. For example, for BigQuery, this specifies information about the BigQuery source.

Fields
dataSourceId
JSON representation

The parameters of the data source, used when querying the data source.

BigQueryDataSourceSpec

The specification of a BigQuery data source that’s connected to a sheet.

Fields
parameters[]
JSON representation

The ID of a BigQuery enabled GCP project with a billing account attached. For any queries executed against the data source, the project is charged.

BigQueryQuerySpec

Specifies a custom BigQuery query.

Fields
projectId
JSON representation

The raw query string.

BigQueryTableSpec

Specifies a BigQuery table definition. Only native tables is allowed.

Fields
rawQuery
JSON representation

The ID of a BigQuery project the table belongs to. If not specified, the projectId is assumed.

The BigQuery table id.

The BigQuery dataset id.

DataSourceParameter

A parameter in a data source’s query. The parameter allows the user to pass in values from the spreadsheet into a query.

Fields
tableProjectId
JSON representation

Named parameter. Must be a legitimate identifier for the DataSource that supports it. For example, BigQuery identifier.

A range that contains the value of the parameter. Its size must be 1×1.

DataSourceRefreshSchedule

Schedule for refreshing the data source.

Fields
name
JSON representation

True if the refresh schedule is enabled, or false otherwise.

Output only. The time interval of the next run.

Daily refresh schedule.

Weekly refresh schedule.

Monthly refresh schedule.

DataSourceRefreshScope

The data source refresh scopes.

Fields
enabled
Enums
DATA_SOURCE_REFRESH_SCOPE_UNSPECIFIEDDefault value, do not use.
ALL_DATA_SOURCESRefreshes all data sources and their associated data source objects in the spreadsheet.

DataSourceRefreshDailySchedule

A schedule for data to refresh every day in a given time interval.

JSON representation

The start time of a time interval in which a data source refresh is scheduled. Only hours part is used. The time interval size defaults to that in the Sheets editor.

TimeOfDay

Fields
startTime
JSON representation

Hours of day in 24 hour format. Should be from 0 to 23. An API may choose to allow the value «24:00:00» for scenarios like business closing time.

Minutes of hour of day. Must be from 0 to 59.

Seconds of minutes of the time. Must normally be from 0 to 59. An API may allow the value 60 if it allows leap-seconds.

Fractions of seconds in nanoseconds. Must be from 0 to 999,999,999.

DataSourceRefreshWeeklySchedule

A weekly schedule for data to refresh on specific days in a given time interval.

Fields
hours
JSON representation

The start time of a time interval in which a data source refresh is scheduled. Only hours part is used. The time interval size defaults to that in the Sheets editor.

Days of the week to refresh. At least one day must be specified.

DayOfWeek

Represents a day of the week.

Fields
startTime
Enums
DAY_OF_WEEK_UNSPECIFIEDThe day of the week is unspecified.
MONDAYMonday
TUESDAYTuesday
WEDNESDAYWednesday
THURSDAYThursday
FRIDAYFriday
SATURDAYSaturday
SUNDAYSunday

DataSourceRefreshMonthlySchedule

A monthly schedule for data to refresh on specific days in the month in a given time interval.

JSON representation

The start time of a time interval in which a data source refresh is scheduled. Only hours part is used. The time interval size defaults to that in the Sheets editor.

Days of the month to refresh. Only 1-28 are supported, mapping to the 1st to the 28th day. At lesat one day must be specified.

Interval

Represents a time interval, encoded as a Timestamp start (inclusive) and a Timestamp end (exclusive).

The start must be less than or equal to the end. When the start equals the end, the interval is empty (matches no time). When both start and end are unspecified, the interval matches any time.

Fields
startTime
JSON representation

Optional. Inclusive start of the interval.

If specified, a Timestamp matching this interval will have to be the same or after the start.

Optional. Exclusive end of the interval.

If specified, a Timestamp matching this interval will have to be before the end.

Methods

batchUpdate

create

getByDataFilter

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Fields
startTime