|
1: 2015-12-14 (月) 12:15:42 iseki |
| + | *** PHP for Google Translator [#x18dcc38] |
| + | <?php |
| + | $api = '....'; |
| + | $ggl = 'https://www.googleapis.com/language/translate/v2'; |
| | | |
| + | $txt = ''; |
| + | $src = ''; |
| + | $dst = ''; |
| + | |
| + | if (isset($_GET['text'])) $txt = htmlentities($_GET['text'], ENT_QUOTES, 'utf-8'); |
| + | if (isset($_GET['fr'])) $src = $_GET['fr']; |
| + | if (isset($_GET['to'])) $dst = $_GET['to']; |
| + | $osrc = $src; |
| + | |
| + | // |
| + | if ($src==='auto' || empty($src)) { |
| + | $langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']); |
| + | $langs = array_reverse($langs); |
| + | foreach($langs as $lang) { |
| + | $ctr = substr($lang, 0, 2); |
| + | if ($ctr!=$dst) { |
| + | $src = $ctr; |
| + | break; |
| + | } |
| + | } |
| + | if ($src==='auto' || empty($src)) { |
| + | if ($dst!=='ja') $src = 'ja'; |
| + | else if ($dst!=='en') $src = 'en'; |
| + | } |
| + | } |
| + | |
| + | // |
| + | if (!empty($txt) && !empty($src) && !empty($dst) && strlen($src)==2 && strlen($dst)==2 && $src!=$dst) { |
| + | // |
| + | $url = $ggl.'?key='.$api.'&q='.rawurlencode($txt).'&source='.$src.'&target='.$dst; |
| + | |
| + | $hndl = curl_init($url); |
| + | curl_setopt($hndl, CURLOPT_RETURNTRANSFER, true); |
| + | $resp = curl_exec($hndl); |
| + | curl_close($hndl); |
| + | |
| + | $decd = json_decode($resp, true); |
| + | |
| + | if (array_key_exists('data', $decd)) { |
| + | echo $decd['data']['translations'][0]['translatedText']; |
| + | } |
| + | else { |
| + | echo 'ERROR : Google Translator returns error!!'; |
| + | error_log('trans.php: osrc = '.$osrc.', src = '.$src.', dist = '.$dst.', text = '.$txt); |
| + | error_log('trans.php: '.print_r($decd, true)); |
| + | } |
| + | } |
| + | else { |
| + | error_log('trans.php: osrc = '.$osrc.', src = '.$src.', dist = '.$dst.', text = '.$txt); |
| + | } |