【问题标题】:Add array form data in google sheets api through PHP通过PHP在google sheet api中添加数组表单数据
【发布时间】:2021-09-02 08:18:53
【问题描述】:

我在 PHP 中使用 google sheet API 将我的 html 表单数据添加到 google 电子表格中。 所有其他数据都已附加到工作表的相应单元格中,因为每个值都有一个数据,除了一个数据在数组中,因为 html 输入数据在多个复选框中。

我的谷歌表格:

还有我在 php 中的代码:

<?php

//add data to google spreadsheet
require __DIR__ . '/vendor/autoload.php';

//getting form data
    $name_kanji = $_POST['name_kanji'];
    $name_katakana = $_POST['name_katakana'];
    $age = $_POST['age'];
    $phone = $_POST['phone'];
    $userEmail = $_POST['email'];
    $zip_code = $_POST['zip_code'];
    $city = $_POST['city'];
    $address1 = $_POST['address1'];
    $address2 = $_POST['address2'];
    $experience = $_POST['experience'];
    $others_text = $_POST['others_text'];
    $lessons = $_POST['check_list'];
    $source = $_POST['source'];

//Reading data from spreadsheet.

$client = new \Google_Client();

$client->setApplicationName('Google Sheets and PHP');

$client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);

$client->setAccessType('offline');

$client->setAuthConfig(__DIR__ . '/credentials.json');

$service = new Google_Service_Sheets($client);


$spreadsheetId = "14B0iB8-uLFNkb_d0qY183wNXeW5reAW5QBjOf69VXeU"; //It is present in the spreadsheet URL

//Adding the data in your google sheet

$update_range = 'data';

$values = [[ $name_kanji, $name_katakana, $age, $phone, $userEmail, $zip_code.', '.$city.', '.$address1.', '.$address2, $experience, $others_text, $lessons, $source]];

$body = new Google_Service_Sheets_ValueRange([
'values' => $values
]);

$params = [
'valueInputOption' => 'RAW'
];

$insert = [
    'insertDataOption' => 'INSERT_ROWS'
];

$update_sheet = $service->spreadsheets_values->append($spreadsheetId, $update_range, $body, $params);

我的问题在于以下代码

$values = [[ $name_kanji, $name_katakana, $age, $phone, $userEmail, $zip_code.', '.$city.', '.$address1.', '.$address2, $experience, $others_text, $lessons, $source]];

这里 $lessons 是在数组中,其数据应该用逗号填充或在电子表格的 I 列中的列表中填充。

我可以得到关于如何传递数组数据的解决方案吗?

【问题讨论】:

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


    【解决方案1】:

    要将您的数组转换为逗号分隔的字符串,请使用例如implode method

    示例:

    $list = implode(', ', $lessons);
    $values = [[ $name_kanji, $name_katakana, $age, $phone, $userEmail, $zip_code.', '.$city.', '.$address1.', '.$address2, $experience, $others_text, $list, $source]];
    

    【讨论】:

    • 它有效,但我怎样才能换行而不是使用逗号?用于换行的html标签显示为逗号而不是换行。
    • 对于换行符,使用'\n' 而不是', ' 作为分隔符。
    • 如果我将, 替换为\n,数据将在谷歌表格中显示为这样的data1\ndata2\ndata3\ndata4
    • 这不是我的经验。在电子表格中,换行符被正确识别和显示。
    猜你喜欢
    • 2020-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    相关资源
    最近更新 更多