Skip to content

Instantly share code, notes, and snippets.

@bakytn
Last active December 17, 2015 00:39
Show Gist options
  • Save bakytn/5523037 to your computer and use it in GitHub Desktop.
Save bakytn/5523037 to your computer and use it in GitHub Desktop.
Quick command line Google Translate
#!/usr/bin/php
<?php
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/26.0.1410.63 Safari/537.11\r\n",
"Referer: http://translate.google.com/\r\n"
)
);
$default_to = "ru";
$default_from = "en";
if ($argv[1] == '-h') {
echo "Usage:\n";
echo "\ttrans <lang code from> <lang code to> <text>\n";
echo "\t or\n";
echo "\ttrans any text to translate goes here\n";
echo "Defaults:\n";
echo "\tlanguage from: $default_from\n";
echo "\tlanguage to: $default_to\n";
die;
}
$context = stream_context_create($opts);
if (empty($argv[2])) {
$from = $default_from;
$to = $default_to;
$text = urlencode($argv[1]);
} else {
$from = $argv[1];
$to = $argv[2];
// if not language specified, then just translate the command line arguments
if ($from != 'en' || $from != 'ru') {
$from = $default_from;
$to = $default_to;
$text = urlencode(join(' ', array_slice($argv, 1)));
} else {
$text = urlencode($argv[3]);
}
}
// Open the file using the HTTP headers set above
$file = file_get_contents('http://translate.google.com/translate_a/t?client=t&text=' . $text . '&hl=en&sl=' . $from . '&tl=' . $to . '&ie=UTF-8&oe=UTF-8&multires=1&ssel=0&tsel=0&sc=1', false, $context);
#if (isset($argv[4])) {
# echo $file;
#}
preg_match('/"([^"]+)"/u', $file, $matches);
$len = strlen($matches[1]);
echo str_repeat("-", $len) . "\n";
echo $matches[1];
echo "\n" . str_repeat("-", $len) . "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment