如何从谷歌翻译API v2 php获取翻译


How get translation from Google Translate API v2 php?

我用 https://github.com/google/google-api-php-client 进行翻译。

当我尝试时

print_r($translation->listTranslations( "John go home", "es" ));

我得到了

Google_Service_Translate_TranslationsListResponse Object
(
    [collection_key:protected] => translations
    [internal_gapi_mappings:protected] => Array
        (
        )
    [translationsType:protected] => Google_Service_Translate_TranslationsResource
    [translationsDataType:protected] => array
    [modelData:protected] => Array
        (
            [data] => Array
                (
                    [translations] => Array
                        (
                            [0] => Array
                                (
                                    [translatedText] => John ir a casa
                                    [detectedSourceLanguage] => en
                                )
                        )
                )
        )
    [processed:protected] => Array
        (
        )
)

但是当我尝试使用 getTranslations() 函数获取翻译时 - 我得到了空数组。请指教!

看起来库坏了。

不过,您可以使用它来获取翻译!

$client = new Google_Client();
$client->setDeveloperKey('xxxx-your-dev-key-xxxx');

$translate = new Google_Service_Translate($client);
$translations = $translate->translations->listTranslations('Hello world!', 'fr');

var_dump($translations->data);
var_dump($translations->data['translations'][0]["translatedText"]);

会给你

array(1) {
  ["translations"]=>
  array(1) {
    [0]=>
    array(2) {
      ["translatedText"]=>
      string(17) "Bonjour le monde!"
      ["detectedSourceLanguage"]=>
      string(2) "en"
    }
  }
}
string(17) "Bonjour le monde!"

我提交了一个解决此问题的 PR,但尚未被接受。