Code Snippet » Google Translater
Posted: Sun Feb 17, 2008 10:45 am
Hello, world!
Here is a piece of code I was planning on putting into the Code Snippet forum, and was directed to post it here first.
It is a simple function that uses cURL to connect to the google translater. It simply sends the first argument to the translation page, under the same conditions as the real form, then returns the results. The second argument is the two character abreviation of the language you want produce. The third, (optional) is what language the input is.
So, what do you think?
Thanks
Here is a piece of code I was planning on putting into the Code Snippet forum, and was directed to post it here first.
It is a simple function that uses cURL to connect to the google translater. It simply sends the first argument to the translation page, under the same conditions as the real form, then returns the results. The second argument is the two character abreviation of the language you want produce. The third, (optional) is what language the input is.
So, what do you think?
Code: Select all
<?php
/****************************\
|Google Translation API |
\****************************/
function google_translate($text, $lang_to, $lang_from='en'){
$lang_to = strtolower($lang_to);
$lang_from = strtolower($lang_from);
$lang_pat = $lang_from .'|'. $lang_to;
$langs = array('ar|en', 'zh|en', 'zh-CN|zh-TW', 'zh-TW|zh-CN', 'nl|en', 'en|ar', 'en|zh-CN', 'en|zh-TW', 'en|nl', 'en|fr', 'en|de', 'en|el', 'en|it', 'en|ja', 'en|ko', 'en|pt', 'en|ru', 'en|es', 'fr|en', 'fr|de', 'de|en', 'de|fr', 'el|en', 'it|en', 'ja|en', 'ko|en', 'pt|en', 'ru|en', 'es|en');
$match = false;
foreach ($langs as $lang){
if ($lang==$lang_pat){
$match = true;
break;
}
}
if ($match){
$curl = curl_init();
$url = 'http://translate.google.com/translate_t?langpair='. $lang_pat;
$post = 'hl=en&ie=UTF8&text='. $text .'&langpair='. $lang_pat;
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
$page = curl_exec($curl);
curl_close($curl);
preg_match('/<div id=result_box dir="ltr">(.*?)<\/div>/i', $page, $matches);
$page = $matches[1];
$page = str_replace('<br>', '
', $page);
return $page;
}else{
echo 'Error: invalid language in str_translate()';
return false;
}
}
?>