PHP + Google api php client + Google spreadsheets API Client и запись в ячейку листа таблицы кириллических символов?

Все php-клиенты перечислил в заголовке вопроса.
Авторизация, доступ к записи таблицы имеется: записываются значения на латинице и цифры.
Никак не получается записать значение, содержащее кириллические символы.
Подобные вопросы уже поднимались на stackoverflow, но решения так и не найдено: тут и тут. Google spreadsheets API Client взят отсюда.

Привожу свой листинг кода:
<?

define('SERVICE_ACCOUNT_CLIENT_ID', 'XXX.apps.googleusercontent.com');
define('SERVICE_ACCOUNT_EMAIL', 'XXXX@developer.gserviceaccount.com');
define('SERVICE_ACCOUNT_PKCS12_FILE_PATH', 'XXXX.p12');

require_once 'google-api-php-client/src/Google/autoload.php';
$accessToken = getGoogleTokenFromKeyFile(SERVICE_ACCOUNT_CLIENT_ID, SERVICE_ACCOUNT_EMAIL, SERVICE_ACCOUNT_PKCS12_FILE_PATH);

use Google\Spreadsheet\DefaultServiceRequest;
use Google\Spreadsheet\ServiceRequestFactory;

$serviceRequest = new DefaultServiceRequest($accessToken);
ServiceRequestFactory::setInstance($serviceRequest);

$spreadsheetService = new Google\Spreadsheet\SpreadsheetService();
$spreadsheetFeed = $spreadsheetService->getSpreadsheets();
$spreadsheet = $spreadsheetFeed->getByTitle('Таблица');

$worksheetFeed = $spreadsheet->getWorksheets();
$worksheet = $worksheetFeed->getByTitle('Лист1');

$listFeed = $worksheet->getListFeed();

$dataz = array();
foreach ($listFeed->getEntries() as $k=>$entry) {
    $values = $entry->getValues();
    if($values['jiraid'] == 'XXX-92'){
      $listEntry = $entry;
     //$values['issuekey'] = '1111'; // так добавляется
     //$values['issuekey'] = 'asd'; // так добавляется
     $values['issuekey'] = 'лол'; // так НЕ добавляется
			// $values['issuekey'] = iconv("UTF-8", "CP1251", "Привет, лист"); // так тоже НЕ добавляется 
      $listEntry->update($values);  
    }
		$dataz[] = $values;
}
print_r($dataz);


/**
 * Retrieves a Google API access token by using a P12 key file,
 * client ID and email address
 *
 * These three things may be obtained from 
 * https://console.developers.google.com/
 * by creating a new "Service account"
 */
function getGoogleTokenFromKeyFile($clientId, $clientEmail, $pathToP12File) {
    $client = new Google_Client();
    $client->setClientId($clientId);

    $cred = new Google_Auth_AssertionCredentials(
        $clientEmail,
        array('https://spreadsheets.google.com/feeds'),
        file_get_contents($pathToP12File)
    );

    $client->setAssertionCredentials($cred);

    if ($client->getAuth()->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion($cred);
    }

    $service_token = json_decode($client->getAccessToken());
    return $service_token->access_token;
}

?>


При попытке аптедейта с кириллицей, выводится ошибка:

Fatal error: Uncaught exception 'Google\Spreadsheet\Exception' with message 'Error in Google Request' in /var/www/project/data/www/project.site.ru/test/jira/google-api-php-client/src/Google/Spreadsheet/DefaultServiceRequest.php:262 Stack trace: #0 /var/www/project/data/www/project.site.ru/test/jira/google-api-php-client/src/Google/Spreadsheet/DefaultServiceRequest.php(178): Google\Spreadsheet\DefaultServiceRequest->execute(Resource id #32) #1 /var/www/project/data/www/project.site.ru/test/jira/google-api-php-client/src/Google/Spreadsheet/ListEntry.php(87): Google\Spreadsheet\DefaultServiceRequest->put('https://spreads...', '<entry xmlns="h...') #2 /var/www/project/data/www/project.site.ru/test/jira/gdrive-test.php(132): Google\Spreadsheet\ListEntry->update(Array) #3 /var/www/project/data/www/project.site.ru/test/jira/jira-webhooks.php(105): include('/var/www/project/...') #4 {main} thrown in /var/www/project/data/www/project.site.ru/test/jira/google-api-php-client/src/Google/Spreadsheet/DefaultServiceRequest.php on line 262


За обновление ячейки отвечает метод google-api-php-client/src/Google/Spreadsheet/DefaultServiceRequest.php:
/**
     * Perform a put request
     * 
     * @param string $url
     * @param mixed  $postData
     * 
     * @return string
     */
    public function put($url, $postData)
    {
        //file_put_contents('1.txt', $postData, LOCK_EX);
        $headers = array(
            'Content-Type: application/atom+xml',
            'Content-Length: ' . strlen($postData),
        );
        $ch = $this->initRequest($url, $headers);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        return $this->execute($ch);
    }


Метод, формирующий xml google-api-php-client/src/Google/Spreadsheet/ListEntry.php:
/**
     * Update this entry
     * 
     * @param array $values
     */
    public function update($values)
    {        
        $entry = '<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gsx="http://schemas.google.com/spreadsheets/2006/extended">';
        $entry .= '<id>'.$this->xml->id->__toString().'</id>';

        foreach($values as $colName => $value) {
            $entry .= sprintf(
                '<gsx:%s><![CDATA[%s]]></gsx:%s>',
                $colName,
                $value,
                $colName
            );
        }

        $entry .= '</entry>';

        ServiceRequestFactory::getInstance()->put($this->getEditUrl(), $entry);
    }


Пытаюсь решить проблему уже который день, но так и не получилось побороть эту напасть.
Задача довольно тривиальная и думаю, что многие, кто работал с Google spreadsheets API, также наткнулись на эти грабли.

Прошу сообщество помочь найти решение.
  • Вопрос задан
  • 8278 просмотров
Пригласить эксперта
Ответы на вопрос 1
@maxyefa
Привет всем. Здесь есть решение.
karl.kranich.org/2015/04/16/google-sheets-api-php
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы