Z
Z
ZHeKKa2015-08-23 16:45:26
PHP
ZHeKKa, 2015-08-23 16:45:26

PHP + Google api php client + Google spreadsheets API Client and writing Cyrillic characters to a sheet cell?

All php clients are listed in the title of the question.
Authorization, access to the table record is available: values ​​are written in Latin and numbers.
It is impossible to write down the value containing Cyrillic characters in any way.
Similar questions have already been raised on stackoverflow, but no solution has been found: here and here . Google spreadsheets API Client taken from here .
Here is my code listing:

<?

define('SERVICE_ACCOUNT_CLIENT_ID', 'XXX.apps.googleusercontent.com');
define('SERVICE_ACCOUNT_EMAIL', '[email protected]');
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;
}

?>

When trying to update with Cyrillic, an error is displayed:
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

The google-api-php-client/src/Google/Spreadsheet/DefaultServiceRequest.php method is responsible for updating the cell:
/**
     * 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);
    }

Method forming 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);
    }

I've been trying to solve the problem for a day now, but I still haven't been able to overcome this scourge.
The task is quite trivial and I think that many who worked with the Google spreadsheets API also stumbled upon this rake.
I ask the community to help find a solution.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
maxyefa, 2016-03-14
@maxyefa

Hi all. There is a solution here.
karl.kranich.org/2015/04/16/google-sheets-api-php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question