Monday, August 28, 2017

Using Google Translation API For Indian Language with PHP

Google translation API works good for Indian languages, if we type in proper language. For example, if you pass following in API. 

कैसे हो

Then it will translate properly to 

how are you

But if you pass it in english, like this.

"KAISE HO"

Then it will send the same text back but it only detects language. So it does not work properly. So what shall the possible solution for it. 

Here is how I worked out in one of my old project.

First I used Google input tools API to convert the input to regional language. 

So steps if First

KAISE HO is converted to

कैसे हो

and then pass it in translation API to convert it to English. Here is the code for the same.

$translatedText = "KAISE HO";
$detectedSourceLanguage = "hi";

$url ='https://www.google.com/inputtools/request?text='.urlencode($translatedText).'&ime=transliteration_en_'.urlencode($detectedSourceLanguage);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_PROXYPORT,3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
$response = curl_exec($ch);
$output = json_decode($response);
$resultText = '';

if($output[0] == 'SUCCESS'){
if(isset($output[1])){
if(isset($output[1][0])){
if(isset($output[1][0][1])){
$resultText = $output[1][0][1][0];
}
}
}
}

if($resultText != ''){
$url ='https://translation.googleapis.com/language/translate/v2';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"q=".urlencode($resultText)."&target=en&key=YOUR_API");

curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_PROXYPORT,3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
$response = curl_exec($ch);
$output = json_decode($response);
$resultText = $output->data->translations[0]->translatedText;
}

Hope this helps you in proper translation.

No comments:

Post a Comment