Неустранимая ошибка: Uncaught Google_Service_Exception API Google Sheets PHP Ошибка добавления строки - PullRequest
0 голосов
/ 12 марта 2020

Получение следующей ошибки:

Fatal error: Uncaught Google_Service_Exception: { "error": { "code": 400, "message": "Invalid JSON payload received. Unknown name \"0\" at 'data.values[1]': Cannot find field.

Странно, но это происходит только тогда, когда массив, который я добавляю, имеет 7-й индекс. См. Полный массив ниже.

array (size=11)
      0 => int 2176
      1 => string '16 Bedroom Residence With Unique Design' (length=39)
      2 => string 'This residence has a proven solid rental income... (length=2224)
      3 => string '2095000' (length=7)
      4 => string '3000' (length=4)
      5 => string '16' (length=2)
      6 => string '16.5' (length=4)
      7 => string 'Tamarindo' (length=9)
      8 => string 'For Sale' (length=8)
      9 => string 'House' (length=5)
      10 => string 'Air Conditioning, BBQ Area, Close to Schools, Close to Shops, Fully Equipped, Fully Furnished, Internet / Wifi, Laundry Room, Parking, Private Garden, Private Pool, ' (length=165)

Вот функция, которую я вызываю для добавления строк:

function insert_google_sheet($data)
{

    require 'vendor/autoload.php';

    $client = new  \Google_Client();
    $client->setApplicationName('Properties Google Sheet');
    $client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
    $client->setAccessType('offline');
    $client->setAuthConfig(__DIR__ . '/credentials.json');
    $service = new Google_Service_Sheets($client);
    $spreadsheetID = '1_3o2B7kucFBNWLJ99CWKCJsePqfZgB2fi8U7AatFoow';

    $range = 'Properties';

    $body = new Google_Service_Sheets_ValueRange([
        'values'    => $data
    ]);
    $params = [
        'valueInputOption' => 'RAW'
    ];
    $insert = [
        'insertDataOption'  => 'INSERT_ROWS'
    ];
    $service->spreadsheets_values->append($spreadsheetID, $range, $body, $params, $insert);

}

Я повторяю, это работает хорошо, если у меня есть только до шестого индекса в массив.

________ РЕДАКТИРОВАТЬ ____________

Сбор данных для вставки в Google Sheets из WordPress сообщения

$insert_data = [];
    // Get Post Info
    $properties = get_posts(array(
        'numberposts'      => -1,
        'orderby'          => 'title',
        'order'            => 'ASC',
        'post_type'        => 'property',
    ));

    foreach ($properties as $property) {
        // Get Post Meta    
        $id = $property->ID;
        $title = $property->post_title;
        $description =  $property->post_content;

        $property_meta = get_post_meta($id);
        $price = $property_meta['_meta_price'][0];
        $area =   $property_meta['_meta_area'][0];
        $beds = $property_meta['_meta_bedroom'][0];
        $baths = $property_meta['_meta_bathroom'][0];
        // $featured = $property_meta['_meta_featured'][0];

        $property_location = get_the_terms($id, 'location');
        $property_location = $property_location[0]->name;

        $property_status = get_the_terms($id, 'status');
        $property_status = $property_status[0]->name;

        $property_type = get_the_terms($id, 'type');
        $property_type = $property_type[0]->name;

        $property_features = get_the_terms($id, 'features');

        if ($property_features) {
            $features = '';
            foreach ($property_features as $feat) {
                $features .=  $feat->name . ', ';
            }
        }

        $data_array = array(
            $id,
            $title,
            $description,
            $price,
            $area,
            $beds,
            $baths,
            $property_location,
            $property_status,
            $property_type,
            $features
        );
        array_push($insert_data, $data_array);
    }

    insert_google_sheet($insert_data);

1 Ответ

0 голосов
/ 14 марта 2020

Он возражает против некоторых входящих данных, но сообщение об ошибке не является более понятным, чем это. Unknown name \"0\" at 'data.values[0]': Cannot find field. - это неправильное направление. Это не обязательно значение [0], которое является проблемой. Моя проблема заключалась в значении NULL в [7] в строке 3. Если вы передаете несколько строк в $ insert_data, проблема в любой из них может быть проблемой. Это будет то же сообщение об ошибке.

Возможно, лист ожидает число в этом столбце? Попробуйте другой пустой лист?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...