Commit 77cb903f authored by Taddeüs Kroes's avatar Taddeüs Kroes

Telemetica: Added assignment 2 code.

parent 4a67180c
#!/usr/bin/php
<?php
// Call Google Translate API
function translate($text, $from, $to) {
$key = "AIzaSyD5sFp2R2IMtDVWdu-4X-TptJCSod0chVc";
$url = sprintf("https://www.googleapis.com/language/translate/v2?key=%s&source=%s&target=%s&q=%s",
$key, $from, $to, urlencode($text));
if( ($response = file_get_contents($url)) === false )
die("Cannot connect to Google Translate server.");
$response = json_decode($response, true);
return $response["data"]["translations"][0]["translatedText"];
}
// Parse input
$argc != 3 && die(sprintf("Usage: %s FROM TO\n", $argv[0]));
list($from, $to) = array_slice($argv, 1);
$lang_format = "/^[a-z]{2}$/i";
if( !preg_match($lang_format, $from) || !preg_match($lang_format, $to) )
die("A language should be specified as two characters.\n");
// Show parsed input
printf("Input language: %s\nOutput language: %s\n",
$from = strtolower($from), $to = strtolower($to));
// Read input
$handle = fopen("php://stdin", "r");
echo "\nEnter the text that you want to translate (use ctrl-D to "
."end the program).\n\nTranslate: ";
while( ($read = fgets($handle)) !== false )
printf("Translation: %s\n\nTranslate: ", translate($read, $from, $to));
fclose($handle);
?>
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment