google spreadsheets php api

Google Sheets API Overview

The Google Sheets API is a RESTful interface that lets you read and modify a spreadsheet’s data. The most common uses of this API include the following tasks:

Below is a list of common terms used in the Sheets API:

The primary object in Google Sheets that can contain multiple sheets, each with structured information contained in cells. Every spreadsheet is represented by a Spreadsheet resource and has a unique spreadsheetId value, containing letters, numbers, hyphens, or underscores. You can find the spreadsheet ID in a Google Sheets URL:

https://docs.google.com/spreadsheets/d/ spreadsheetId /edit#gid=0

A page or tab within a spreadsheet. Each sheet is represented by a Sheet resource and has a unique title and numeric sheetId value. You can find the sheet ID in a Google Sheets URL:

An individual field of text or data within a sheet. Cells are arranged in rows and columns, and can be grouped together as a range of cells. Each cell is represented by a CellData resource, but doesn’t have a unique ID value. Instead, cells are identified by their row and column coordinates.

A syntax used to define a cell or range of cells with a string that contains the sheet name and starting and ending cell coordinates using column letters and row numbers. This method is most common and useful when referencing an absolute range of cells.

Show examples

A syntax used to define a cell or range of cells with a string that contains the sheet name and starting and ending cell coordinates using row numbers and column numbers. This method is less common, but can be useful when referencing a range of cells relative to a given cell’s position.

Show examples

A defined cell or range of cells with a custom name to simplify references throughout an application. A named range is represented by a FilterView resource.

A defined cell or range of cells that cannot be modified. A protected range is represented by a ProtectedRange resource.

Next steps

To get started with the Google Sheets API:

To learn about developing with Google Workspace APIs, including handling authentication and authorization, refer to Get started as a Workspace developer.

To learn how to configure and run a simple Sheets API app, read the Quickstarts overview.

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 spreadsheets php api

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 spreadsheets php api. Смотреть фото google spreadsheets php api. Смотреть картинку google spreadsheets php api. Картинка про google spreadsheets php api. Фото google spreadsheets php api

(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.

Источник

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.

Источник

Работа с 4 версией API Google таблицы на php

В данной статье будет показана работа с API Google таблицы на php. Мы рассмотрим требования необходимые для использования API, расскажем как создать отдельный проект с доступом к API Google таблицы и сервисные учетные данные с ключом доступа. И конечно же приведем примеры работы с API Google таблицы на php.

Требования для работы с API Google таблицы на php

К работе с API с помощью PHP предъявляются следующие минимальные требования:

Чтобы проверить версию php:

Чтобы установить расширение php-json выполните на CentOS (RedHat подобных):

На Ubuntu подобных системах:

Если у вас установлен composer, то установите расширение с помощью него:

Я же просто скачаю его. Для этого создам папку под проект и перейду в нее:

На этой странице выбираем последнюю версию для версии нашего php и копируем ссылку. В моем случае это версия клиента 2.7.2 для php 7.0. После этого скачиваем архив:

И разархивируем его:

На этом подготовительный этап закончен, переходим к получению доступа к API.

Получение доступа к API Google таблицы

Для начала создадим отдельный проект, в котором в дальнейшем разрешим работу API Google таблиц. Переходим по ссылке и нажимаем CREATE PROJECT (создать проект):

В поле Project name* укажем название название нового проекта, например Sheets и нажимаем CREATE:

На создание нового проекта может потребоваться до нескольких минут. После этого он появится в панели менеджера:

Далее требуется разрешить работу с API Google таблицы для нашего проекта. Переходим через консоль (три черты в верхнем левом углу) в APIs & Services и далее в Dashboards:

Проверяем, что выбран наш проект Sheets и нажимаем ENABLE APIS AND SERVICES:

Откроется страница со всеми API сервисами. Воспользуемся поиском указав Google Sheets API. Кликаем на единственный результат:

И нажимаем кнопку ENABLE:

Далее требуется создать сервисный аккаунт для доступа к API Google страницы. Через консоль выбираем APIs & Services и Credentials:

В появившемся окне выбрать CREATE CREDNTIALS и выбираем Service Account:

После этого открываем только что созданный аккаунт и в раздели ключей создаем новый выбирая Create new key:

Примеры работы с API Google таблицы на php

Создадим таблицу. Для этого перейдем в раздел Google таблицы по ссылке и выберем пустой документ. После того, как таблица была создана необходимо предоставить доступ нашему сервисному аккаунту на её редактирование. Для этого нажимаем кнопку Настройки Доступа в верхнем правом углу и указываем там почту сервисного аккаунта, которую мы скопировали на предыдущем этапе, указав при этом роль Редактор.

Получение идентификатора таблицы и идентификатора листа

Обратите внимание на адресную строку, из которой нам необходимо будет записать два параметра идентификатор таблицы ($spreadsheetId) и идентификатор листа ($sheetId):

Подключение клиента для работы с API Google таблицы

Приступаем к коду на php. Создадим файл sheet.php в нашей рабочей директории. Структура файлов должны иметь следующий вид:

где sheet.php – наш рабочий файл, service_key.json – ключ сервисного аккаунта, а остальные файлы и каталоги – клиент Google таблиц, который мы получили из архива.

Откроем файл sheet.php и запишем следующий код (замените $spreadsheetId на свой):

Данный код по подключению клиента, разрешению доступа и указания идентификатора таблицы будет необходим для запуска всех примеров. Но чтобы его не дублировать, в дальнейшем он будет опускаться.

API Google таблиц имеет ограничение в 500 запросов на проект в течение 100 секунд и 100 запросов за 100 секунд на один сервисный аккаунт! Имейте это в виду при обращении к сервису, при необходимости делайте паузы в коде!

Проверка доступа к API Google таблицы

Добавим к нашему коду следующие строки:

Если все сделано правильно, то после запуска скрипта на экран будет выведена информация о таблице. Но в первый раз может быть следующая ошибка:

Она связана с некорректной структурой файла service_key.json: проверьте, чтобы в нем было переносов строк, а в параметре private_key в описании начала и конца ключа (BEGIN PRIVATE KEY и END PRIVATE KEY) между словами было строго по одному пробелу.

Получение данных таблицы, листов и их содержимого

Для примера будет использована таблицы с именем My project с одним листом 2020-10 и данными:

Посмотрим эти данные через API:

Результатом работы будут следующие данные:

Создание новой таблицы

Для примера приведет метод создания новой таблицы:

Однако, если вы перейдете url вам будет отказано в доступе. Необходимо разрешить чтение/ редактирование с вашего Google аккаунта.

Разрешения на доступ к таблице

Теперь мы можем добавить доступ:

Теперь мы можем перейти по url из предыдущего примера и редактировать таблицу.

Проверка прав доступа к таблице/файлу

Для проверки, какие права (роли) у нас есть на таблицу (файл) можно воспользоваться следующим примером:

Создание нового листа

Cоздадим в нашей таблице новый лист с именем NEW:

Изменение свойств листа

Изменим свойства нового листа, например, переименуем его:

Копирование листа

Метод позволяет скопировать лист таблицы в эту же электронную таблицу или другую:

В нашей таблице появится новый лист с идентификатором 1 и именем 2020-10 (копия).

Получение содержимого листа

Чтобы получить содержимое всего листа необходимо указать его имя:

Мы получим следующий ответ:

Получение содержимого диапазона ячеек

Обновление диапазона ячеек

Допустим, мы хотим добавить ещё одну строку с данными данными в диапазон A5:E5:

По умолчанию, при вставке диапазона используется majorDimension = ROWS, т.е. диапазон заполняется построчно. Если требуется вставка по столбцам, необходимо изменить его значение на COLUMNS:

Если необходимо пропустить (не заполнять) строку / столбец, то в массиве значений указывается пустой массив:

В этом случае значения строки / столбца останутся первоначальными.

Очистка диапазона ячеек

Очистим диапазон ячеек, которые мы обновили в предыдущем примере:

Заключение

В этой статье рассмотрена лишь малая часть возможностей по работе с API Google страницы на php. При необходимости буду стараться добавлять новые примеры по взаимодействию с сервисом. Если у кого-то возникнет необходимость в конкретных – пишите, буду рад помочь.

Источник

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

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