【问题标题】:Google Translate API v2, v3 PHP谷歌翻译 API v2、v3 PHP
【发布时间】:2019-09-23 13:38:51
【问题描述】:

我刚刚开始使用 BING 翻译 API 对其大多数支持的语言进行少量翻译,效果非常好。

有一个 GitHub 项目,其中包含用于向 Microsoft 调用 API 的简单 PHP 代码。您通常只需要 API 密钥,并且可以很容易地对其进行自定义。

Text-Translation-API-V3-PHP

// NOTE: Be sure to uncomment the following line in your php.ini file.
// ;extension=php_openssl.dll
// **********************************************
// *** Update or verify the following values. ***
// **********************************************
// Replace the subscriptionKey string value with your valid subscription key.
$key = 'ENTER KEY HERE';
$host = "https://api.cognitive.microsofttranslator.com";
$path = "/translate?api-version=3.0";

// Translate to German and Italian.
$params = "&to=de&to=it";
$text = "Hello, world!";

if (!function_exists('com_create_guid')) {
  function com_create_guid() {
    return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
        mt_rand( 0, 0xffff ),
        mt_rand( 0, 0x0fff ) | 0x4000,
        mt_rand( 0, 0x3fff ) | 0x8000,
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
    );
  }
}

function Translate ($host, $path, $key, $params, $content) {
    $headers = "Content-type: application/json\r\n" .
        "Content-length: " . strlen($content) . "\r\n" .
        "Ocp-Apim-Subscription-Key: $key\r\n" .
        "X-ClientTraceId: " . com_create_guid() . "\r\n";
    // NOTE: Use the key 'http' even if you are making an HTTPS request. See:
    // http://php.net/manual/en/function.stream-context-create.php
    $options = array (
        'http' => array (
            'header' => $headers,
            'method' => 'POST',
            'content' => $content
        )
    );
    $context  = stream_context_create ($options);
    $result = file_get_contents ($host . $path . $params, false, $context);
    return $result;
}

$requestBody = array (
    array (
        'Text' => $text,
    ),
);
$content = json_encode($requestBody);
$result = Translate ($host, $path, $key, $params, $content);
// Note: We convert result, which is JSON, to and from an object so we can pretty-print it.
// We want to avoid escaping any Unicode characters that result contains. See:
// http://php.net/manual/en/function.json-encode.php
$json = json_encode(json_decode($result), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
echo $json;

我也有一个 Google Cloud 帐户,并且正在寻找 Google 支持但 BING 不支持的几种语言的类似内容。对于 v2,调用谷歌返回翻译并不难。

我发现这个 GitHub 项目似乎适用于使用 API 密钥的 v2 API 调用,但不幸的是,我认为现在这是一个按服务收费的计划?

google-cloud-php-translate

如果您有 API 密钥,这似乎也很有效。如果您使用的是 v3,他们显然更新了库和支持。您可以从命令行进行 CURL 调用,他们的网站上有一些记录,但我正在寻找一种使用 PHP 文件进行调用的方法。

require 'vendor/autoload.php';   
use Google\Cloud\Translate\TranslateClient;

$translate = new TranslateClient([
    'key' => 'APIKEY'
]);

// Translate text from english to french.
$result = $translate->translate('Hello world!', [
    'target' => 'fr'
]);

echo $result['text'] . "\n";

// Detect the language of a string.
$result = $translate->detectLanguage('Greetings from Michigan!');

echo $result['languageCode'] . "\n";

// Get the languages supported for translation specifically for your target language.
$languages = $translate->localizedLanguages([
    'target' => 'en'
]);

foreach ($languages as $language) {
    echo $language['name'] . "\n";
    echo $language['code'] . "\n";
}

// Get all languages supported for translation.
$languages = $translate->languages();

foreach ($languages as $language) {
    echo $language . "\n";
}

不确定这是否可行,但我能想到的最好的方法是基于命令行 CURL,但身份验证错误并失败。我确实有我的项目/服务凭据的 .json 文件。我认为 ${PROJECT_ID} 是该帐户的项目 ID,而 Bearer $(gcloud auth application-default print-access-token) 我不确定。有一些关于如何通过 CLI 获得它的说明,但是有没有办法通过 PHP 文件获得它?就像我说的,v2 版本运行良好。

$ch = curl_init();   
curl_setopt($ch, CURLOPT_URL, "https://translation.googleapis.com/v3beta1/projects/${PROJECT_ID}/locations/global:detectLanguage");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\n     mimeType: 'text/plain',\n     content: 'Omnia Gallia est divisa in tres partes'\n}");
curl_setopt($ch, CURLOPT_POST, 1);

$headers = array();
$headers[] = 'Authorization: Bearer $(gcloud auth application-default print-access-token)';
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
} else {
    echo $result;
}
curl_close ($ch);

这里可能有线索,但它谈到了导出凭据文件的路径以及从命令行而不是从服务器运行 PHP 脚本。

Google Cloud Translate API Samples

【问题讨论】:

    标签: php curl google-translation-api bing-translator-api


    【解决方案1】:

    我不喜欢使用客户端库,所以我没有安装Google PHP library。据我所知,让身份验证工作的唯一方法是实际完成整个 Oauth2 过程。我认为 PHP 库会为您处理其中的一些问题,但这段代码应该作为独立的解决方案工作。

    首先,确保您已设置 Google Cloud Platform 帐户,然后创建一个项目,然后启用 Translation API,然后,在创建和配置 OAuth 2.0 客户端之前创建和配置 API 密钥(确保您输入正确的重定向网址)。没关系! ;-)

    如果你成功解决了所有这些问题,你应该很高兴!

    该页面有效地将用户重定向到他们刚刚访问的同一页面,但在 url 中包含 GET 请求的结果。响应包含一个代码,可用于发出另一个 GET 请求以检索访问令牌,一旦您获得访问令牌,您就可以发出 POST 请求来执行实际的翻译。

    <?php
    
    $clientId = "{your client id}";
    $clientSecret = "{your client secret}";
    $clientRedirectURL = "{your redirect URL}";
    $login_url = 'https://accounts.google.com/o/oauth2/v2/auth?scope=' . urlencode('https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/cloud-translation') . '&redirect_uri=' . urlencode($clientRedirectURL) . '&response_type=code&client_id=' . $clientId . '&access_type=online';
    
    if (!isset($_GET['code'])){
        header("location: $login_url");
    } else {
        $code = filter_var($_GET['code'], FILTER_SANITIZE_STRING);  
        $curlGet = '?client_id=' . $clientId . '&redirect_uri=' . $clientRedirectURL . '&client_secret=' . $clientSecret . '&code='. $code . '&grant_type=authorization_code';
        $url = 'https://www.googleapis.com/oauth2/v4/token' . $curlGet;
    
        $ch = curl_init($url);      
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);        
        curl_setopt($ch, CURLOPT_POST, 1);      
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        $data = curl_exec($ch); 
        $data = json_decode($data, true);   
        curl_close($ch);
    
        $accessToken = $data['access_token'];
        $apiKey = "{your api key}";
        $projectID = "{your project id}";
    
        $target = "https://translation.googleapis.com/v3/projects/$projectID:translateText?key=$apiKey";
    
        $headers = array( 
            "Content-Type: application/json; charset=utf-8", 
            "Authorization: Bearer " . $accessToken,
            "x-goog-encode-response-if-executable: base64",
            "Accept-language: en-US,en;q=0.9,es;q=0.8"
        );
    
        $requestBody = array();
        $requestBody['sourceLanguageCode'] = "en";
        $requestBody['targetLanguageCode'] = "pt";
        $requestBody['contents'] = array("So, I guess this thing works?");
        $requestBody['mimeType'] = "text/plain";
    
        $ch = curl_init($target);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestBody)); 
        $data = curl_exec($ch);
    
        curl_close($ch);
        echo $data;
    }
    

    另外,我发现this tutorial 很有帮助。

    【讨论】:

    • 这不是不合理的,它是完美的逻辑,像谷歌这样的 SDK 会在你的项目中添加数千个(10000+ 个文件,如果是像 OAuth 那样的谷歌 SDK)来做一些需要 5 行代码的事情...
    【解决方案2】:

    这可能不会评估:

    'Authorization: Bearer $(gcloud auth application-default print-access-token)'
    

    其实是这样的:

    // $cmd = 'gcloud auth application-default login';
    $cmd = 'gcloud auth application-default print-access-token';
    $token = shell_exec($cmd);
    

    此外,它可能应该是service account

    似乎google/cloud 取代了google/cloud-translate。对于Translate,您可以编辑translate-v2.json 或添加translate-v3beta1.json;但是v3beta1 有一个完全不同于v2 的REST API ...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-17
      • 2018-12-25
      • 2012-01-26
      • 2017-04-29
      • 2011-06-06
      • 2012-08-06
      • 1970-01-01
      相关资源
      最近更新 更多