google sheets api php

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.

Источник

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

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

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

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

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

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

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

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

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

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

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

Источник

Работа с 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. При необходимости буду стараться добавлять новые примеры по взаимодействию с сервисом. Если у кого-то возникнет необходимость в конкретных – пишите, буду рад помочь.

Источник

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

Источник

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

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