如何在Google Translate api php中设置ApplicationDefaultCredentials?

如何在Google Translate api php中设置ApplicationDefaultCredentials?,php,google-cloud-platform,google-translate,google-translation-api,Php,Google Cloud Platform,Google Translate,Google Translation Api,我正在尝试在我的服务器上设置谷歌翻译API。 但代码返回错误“无法构造ApplicationDefaultCredentials” 我已经花了很多时间来设置它,但没有结果。 请帮助我您可以在配置变量中传递凭据,然后初始化客户端 <?php require __DIR__ . '/vendor/autoload.php'; use Google\Cloud\Translate\V2\TranslateClient; /** Uncomment and populate these v

我正在尝试在我的服务器上设置谷歌翻译API。 但代码返回错误“无法构造ApplicationDefaultCredentials”

我已经花了很多时间来设置它,但没有结果。
请帮助我

您可以在配置变量中传递凭据,然后初始化客户端


<?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");


?>

Php putenv

Andrey这在Windows 10 Pro上对我有效。Wampserver 3.2.0。PHP7.4.4。它肯定有Windows反斜杠的问题。向前斜杠和避免双引号和单引号在一起有助于提高编译器的性能

    $file = trim("C:/users/boss/onedrive/desktop/google.json",'"');
    putenv("GOOGLE_APPLICATION_CREDENTIALS=$file");
Source language: en
Translation: 翻訳するテキスト

    $file = trim("C:/users/boss/onedrive/desktop/google.json",'"');
    putenv("GOOGLE_APPLICATION_CREDENTIALS=$file");