[英]How set ApplicationDefaultCredentials in Google Translate api php?
我正在尝试在我的服务器上设置谷歌翻译 API。 但代码返回错误“无法构造 ApplicationDefaultCredentials”
$translationClient = new Google\Cloud\Translate\V3\TranslationServiceClient();
putenv('GOOGLE_APPLICATION_CREDENTIALS="/path/to/credetials.json"');
$content = ['one', 'two', 'three'];
$targetLanguage = 'es';
$response = $translationClient->translateText(
$content,
$targetLanguage,
TranslationServiceClient::locationName('[ProjectID]', 'global')
);
$res = '';
foreach ($response->getTranslations() as $key => $translation) {
$separator = $key === 2
? '!'
: ', ';
$res .= $translation->getTranslatedText() . $separator;
}
} catch(\Exception $e) {
$res = $e->getMessage();
}
die(json_encode($res));
我已经花了很多时间来设置它,但没有结果。 请帮我
您可以在配置变量中传递凭据,然后初始化客户端。
<?php
require __DIR__ . '/vendor/autoload.php';
use Google\Cloud\Translate\V2\TranslateClient;
/** Uncomment and populate these variables in your code */
$config = ['credentials' => 'key.json'];
$text = "The text to translate.";
$targetLanguage = "ja";
$translate = new TranslateClient($config);
$result = $translate->translate($text, [
"target" => $targetLanguage,
]);
print("Source language: $result[source]\n");
print("Translation: $result[text]\n");
?>
Source language: en
Translation: 翻訳するテキスト
Php putenv https://www.php.net/manual/en/function.putenv.php
Andrey 这在 Windows 10 Pro 上对我有用。 Wampserver 3.2.0。 Php 7.4.4。 Windows 反斜杠肯定有问题。 正斜杠和避免双引号和单引号一起帮助了编译器。
$file = trim("C:/users/boss/onedrive/desktop/google.json",'"');
putenv("GOOGLE_APPLICATION_CREDENTIALS=$file");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.