【问题标题】:Can I use Google Spreadsheet as a database for my PHP application?我可以使用 Google 电子表格作为我的 PHP 应用程序的数据库吗?
【发布时间】:2017-12-29 17:42:46
【问题描述】:

我有数据库 Google 电子表格。如何使用 PHP 或任何编程语言处理我的数据库?我需要将数据库移动到其他数据库吗?例如:MySQL

【问题讨论】:

  • 您可以使用 google sheet api 使用多种编程语言处理您的电子表格,查看developers.google.com/sheets/api
  • 电子表格不是数据库。你为什么要这样做?
  • 您可能需要查看这些教程 12,了解如何将数据存储到 Google 电子表格。您还可以检查此SO post,它建议将电子表格发布为公开,通过手动编辑 URL(即output=csv)将输出更改为 csv(从默认 HTML),获取它,然后逐行遍历它行使用fgetcsv
  • 我只是想用编程语言处理数据,我认为它更容易

标签: php google-sheets google-spreadsheet-api


【解决方案1】:

我建议您迁移到 MySQL 数据库,特别是对于 PHP,它们运行良好,而且我认为它更可靠 - Google 的服务有一些奇怪的怪癖,可能会很痛苦(例如数据流的上限,这可能会变得非常不方便或昂贵)。此外,如果您的主机在 Apache 上运行,MySQL 在那里运行得非常好,无需手动设置这些服务。无需外包。

如果您使用 MySQL,您正在寻找一个非常简单(以及面向对象编程或过程方法)的接口。您可以使用csv 文件将您在 Google 电子表格中的当前数据导入 MySQL 数据库。

例如,您的连接如下所示:

OOP:

$_connection = new mysqli(host, user, password, database);

程序:

$_connection = mysqli_connect(host, user, password, database);

然后您可以使用简单的查询从数据库中SELECT 值,:

OOP:

$sql = "SELECT row1, row2, row3 FROM table";

if ($result = $_connection->query( $sql ))
{
    if ($result->num_rows > 0)
    {
        while ($row = $result->fetch_assoc())
        {
            //... get using the associate method
            echo $row['row1'];
            // etc...
        }
    }
}

程序:

$sql = "SELECT row1, row2, row3 FROM table";
$result = mysqli_query($_connection, $sql);
$row = mysqli_fetch_assoc($result);
echo $row['row1'];

所以我确实建议您开始使用 MySQL。很简单,有很多文档。

如果您有兴趣,可以从here 找到官方的 PHP 文档。

如果您仍想使用 Google 电子表格,请继续阅读,您会发现更多信息。


但是,正如您所说的任何编程语言,我建议您查看 Python。如果您精通 Python,或者您愿意学习它,您可以通过 tutorial from Twilio 向您尝试的方向迈进。

本教程将引导您了解您需要什么以及如何获得这些依赖项,但只是一个快速概述:

您需要来自 Google API 的 gspreadoauth2client。这是一个简单的命令 - 假设你有 pip:

pip install gspread oauth2client

根据 Twilio,您需要它们:

  1. oauth2client – 使用 OAuth 2.0 通过 Google Drive API 进行授权
  2. gspread – 与 Google 电子表格进行交互(如果您对使用 gspread 很认真,请查看 their documentation,它们非常全面)

安装后,您可以继续从 Google 获得正确的身份验证,您将使用 Google Drive API。 Twilio 向您展示了如何做到这一点。

假设您拥有正确的依赖项,并且您已使用 Google Drive API 授权您的应用,那么您就可以开始获取代码了:

import gspread
from oauth2client.service_account import ServiceAccountCredentials


# use creds to create a client to interact with the Google Drive API
scope = ['https://spreadsheets.google.com/feeds']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client = gspread.authorize(creds)

# Find a workbook by name and open the first sheet
# Make sure you use the right name here.
sheet = client.open("Copy of Legislators 2017").sheet1

# Extract and print all of the values
list_of_hashes = sheet.get_all_records()
print(list_of_hashes)

【讨论】:

    猜你喜欢
    • 2016-04-28
    • 1970-01-01
    • 1970-01-01
    • 2013-04-05
    • 1970-01-01
    • 1970-01-01
    • 2012-04-16
    • 2019-11-07
    • 1970-01-01
    相关资源
    最近更新 更多