Sham
Sham

Reputation: 23

Translate array with google translator

I use below PHP code in Laravel to translate one sentence or paragraph from one input field:

    $apiKey = env('GOOGLE_TRANSLATOR_API');
    $url = env('GOOGLE_TRANSLATOR_LINK') . $apiKey . '&q=' . rawurlencode($name) . '&target='.$language;
    $handle = curl_init($url);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($handle);
    $responseDecoded = json_decode($response, true);
    
    return $responseDecoded['data']['translations'][0]['translatedText'];

and it works perfectly fine.

But now I have two input fields (name and description) and I want to translate both of those fields using one API call and show the results individually.

EDIT

I have tried to use array in the API request as below:

    $apiKey = env('GOOGLE_TRANSLATOR_API');
    $url = env('GOOGLE_TRANSLATOR_LINK') . $apiKey . '&q=' . array('sentence one', 'sentence two) . '&target='.$language;
    $handle = curl_init($url);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($handle);
    $responseDecoded = json_decode($response, true);
    
    return $responseDecoded['data']['translations'][0]['translatedText'];

But I get Array to string conversion error.

Upvotes: 0

Views: 1933

Answers (1)

JEJ
JEJ

Reputation: 904

1Installing the Basic Client Libraries Client library PHP

composer require google/cloud-translate

and in your code

    use Google\Cloud\Translate\V3\TranslationServiceClient;

$translationServiceClient = new TranslationServiceClient();

/** Uncomment and populate these variables in your code */
// $text = 'Hello, world!';
// $textTwo = 'My name is John':
// $targetLanguage = 'fr'; // your lang
// $projectId = '[Google Cloud Project ID]';
$contents = [$text, $textTwo];
$formattedParent = $translationServiceClient->locationName($projectId, 'global');

try {
    $response = $translationServiceClient->translateText(
        $contents,
        $targetLanguage,
        $formattedParent
    );
    // Display the translation for each input text provided
    foreach ($response->getTranslations() as $translation) {
        printf('Translated text: %s' . PHP_EOL, $translation->getTranslatedText());
    }
} finally {
    $translationServiceClient->close();
}

View Code in Github

Upvotes: 1

Related Questions