0

According to google and Sitepoint, there are possibilities to translate multiple text strings in one request. However when I tried to translate multiple strings, it resulted in replacing the first string by the last one.

    $handle = curl_init();

    if (FALSE === $handle)
       throw new Exception('failed to initialize');

curl_setopt($handle, CURLOPT_URL,'https://www.googleapis.com/language/translate/v2');
curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_POSTFIELDS, array('key'=> $apiKey, 'q' => $heading, 'q' => $content, 'source' => $sl, 'target' => $hl));
curl_setopt($handle,CURLOPT_HTTPHEADER,array('X-HTTP-Method-Override: GET'));
$response = curl_exec($handle);
$responseDecoded = json_decode($response, true);
$responseCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);
if($responseCode != 200) {
    header("HTTP/1.0 404 Not Found");
    include_once("ErrorDocument/404.html");
    exit();
}else{
    $heading = $responseDecoded['data']['translations'][0]['translatedText'];
    $content = $responseDecoded['data']['translations'][1]['translatedText'];
}

Any ideas?

Martin Joneš
  • 97
  • 2
  • 13
  • You have multiple keys `q`, the second overwrites the first. – pokeybit Jul 25 '17 at 12:04
  • Try `'q' => array($heading,$content)` – pokeybit Jul 25 '17 at 12:05
  • pokeybit - I havent found this solution on the internet, but I will try. Thanks for the tip. EDIT: nope, just gives following notice "Notice: Array to string conversion" – Martin Joneš Jul 25 '17 at 12:26
  • pokeybit - PHP generates the Notice, but data is sent and received. But only word "Array" is received and no secondary "translatedText" is generated by google as in their documentation. This is how it looks like when i make var_dump() with received data - `array(1) { [0]=> array(1) { ["translatedText"]=> string(5) "Array" } }` – Martin Joneš Jul 25 '17 at 12:37
  • Try `CURLOPT_POSTFIELDS, http_build_query(array('q' => array($heading,$content),etc....))` – pokeybit Jul 25 '17 at 12:40
  • pokeybit - With that code, google responses with HTTP error 400 and custom error message "Required Text" – Martin Joneš Jul 25 '17 at 13:05
  • https://stackoverflow.com/a/5224895/2311317 Try the method in this post – pokeybit Jul 25 '17 at 13:12
  • pokeybit - But there is still the thing that the "q" parameter gets overwritten or replaced. `curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query(array('key'=> $apiKey, /*'q' => array($heading,$content),*/ 'q' => $heading, 'q' => $content, 'source' => $sl, 'target' => $hl)));` This line works only for one of q parameters. By deleting the q parameters and uncommenting your array with two q parameters, it gets 400 error from google saying "Required text" – Martin Joneš Jul 25 '17 at 13:17
  • If you're in a situation where you can install an additional library, [google-cloud-php-translate](https://github.com/GoogleCloudPlatform/google-cloud-php-translate) handles this situation for you. – jdp Jul 25 '17 at 14:13
  • If you prefer to use raw cURL, you will probably need to build the json value of `CURLOPT_POSTFIELDS` manually, as pretty much anything you do in PHP will result in the keys overriding one another. – jdp Jul 25 '17 at 14:14
  • jdp - unfortunately I am not. There really isn't any solution for that? – Martin Joneš Jul 25 '17 at 14:15
  • Use this (https://stackoverflow.com/a/5224895/2311317) method and build the path manually (without PHP array) so you don't duplicate keys – pokeybit Jul 25 '17 at 14:30
  • pokeybit - makes no difference. I am still defining 2 "q" strings, Where the second one replaces the first one. – Martin Joneš Jul 25 '17 at 15:05

2 Answers2

3
    $handle = curl_init();

if (FALSE === $handle)
   throw new Exception('failed to initialize');

curl_setopt($handle, CURLOPT_URL,'https://www.googleapis.com/language/translate/v2');
curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
$data = array('key' => $apiKey,
                'q' => array($heading,$content),
                'source' => $sl,
                'target' => $hl);
curl_setopt($handle, CURLOPT_POSTFIELDS, preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '=', http_build_query($data)));
curl_setopt($handle,CURLOPT_HTTPHEADER,array('X-HTTP-Method-Override: GET'));
$response = curl_exec($handle);
$responseDecoded = json_decode($response, true);
$responseCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);
if($responseCode != 200) {
    header("HTTP/1.0 404 Not Found");
    include_once("ErrorDocument/404.html");
    echo 'Fetching translation failed! Server response code:' . $responseCode . '<br>';
    echo 'Error description: ' . $responseDecoded['error']['errors'][0]['message'] . '<br>';
    echo 'Please contact website administrator';
    exit();
}else{
    $heading = $responseDecoded['data']['translations'][0]['translatedText'];
    $content = $responseDecoded['data']['translations'][1]['translatedText'];
}

This works well for me. Found solution out there. Hope this will help anyone in the future.

Martin Joneš
  • 97
  • 2
  • 13
0

Use library GoogleTranslateForFree

"Library for free use Google Translator. With attempts connecting on failure and array support."

falselight
  • 527
  • 7
  • 11