如何从Google Translate API v2 php获得翻译?

时间:2016-02-22 21:00:03

标签: php google-api-php-client google-translate

我使用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()函数进行翻译时 - 我得到了空数组。请指教!

1 个答案:

答案 0 :(得分:4)

看起来图书馆坏了。

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

$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 that fixes this,但尚未被接受。