Skip to content

Instantly share code, notes, and snippets.

@tuanpht
Last active May 4, 2018 05:16
Show Gist options
  • Save tuanpht/880c59382c748faac145ea98554f1d01 to your computer and use it in GitHub Desktop.
Save tuanpht/880c59382c748faac145ea98554f1d01 to your computer and use it in GitHub Desktop.
<?php
$text = $argv[1];
$postdata = http_build_query([
'q' => $text,
]);
$opts = [
'http' => [
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata,
],
];
$context = stream_context_create($opts);
$url = 'http://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=en&dt=t&ie=UTF-8&oe=UTF-8';
$resultText = file_get_contents($url, false, $context);
$resultText = preg_replace('/,+/', ',', $resultText);
$results = json_decode($resultText);
if (is_array($results) && count($results) > 0) {
foreach ($results[0] as $result) {
echo str_replace("\n", '<br>', $result[0]);
}
}
echo "<hr><a href='https://translate.google.com/#auto/en/$text'>Open in Google Translate</a>";
# From http://www.webupd8.org/2016/03/translate-any-text-you-select-on-your.html
#!/usr/bin/env bash
text="$(xsel -o)"
translate="$(wget -U "Mozilla/5.0" -qO - "http://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=en&dt=t&q=$(echo $text | sed "s/[\"'<>]//g")" | sed "s/,,,0]],,.*//g" | awk -F'"' '{print $2, $6}')"
echo "$translate"
[
[
["We updated the voice blog \"Monsters at 3 o'clock AM\".\n\n","ボイスブログ「午前三時の独壇場」を更新しました。\n\n",,,3],
["This week is the 100th entrance","今週は第参百弐拾参場",,,3]
],,"ja",,,,0.96649998,,[["ja"],,[0.96649998],["ja"]]
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment