<?php

// Usage
// php -f /path/to/google-goldendict.php "words you want to translate
// In GoldenDict go to Dictionaries/Programs, choose "Add..."
// name: Google translation
// Type: HTML
// Command Line: php -f /path/to/google-goldendict.php %GDWORD%

$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=vi&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", '
        ', $result[0]);
    }
}
echo "<hr><a href='https://translate.google.com/#auto/en/$text'>Open in Google Translate</a>";