Google Translate API第2版,第3版PHP

时间:2019-05-05 21:00:28

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

我刚刚开始使用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,调用Google来返回翻译并不难。

我发现这个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,而不确定$(gcloud auth application-default print-access-token)Bearer。关于如何通过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

2 个答案:

答案 0 :(得分:0)

这可能不会评估:

public class TypeWriter extends android.support.v7.widget.AppCompatTextView {

private CharSequence mText;
private int mIndex;
private long mDelay = 150; // in ms

public TypeWriter(Context context) {
    super(context);
}

public TypeWriter(Context context, AttributeSet attrs) {
    super(context, attrs);
}

private Handler mHandler = new Handler();

private Runnable characterAdder = new Runnable() {

    @Override
    public void run() {
        setText(mText.subSequence(0, mIndex++));

        if (mIndex <= mText.length()) {
            mHandler.postDelayed(characterAdder, mDelay);
        }
    }
};

public void animateText(CharSequence txt) {
    mText = txt;
    mIndex = 0;

    setText("");
    mHandler.removeCallbacks(characterAdder);
    mHandler.postDelayed(characterAdder, mDelay);
}

public void setCharacterDelay(long m) {
    mDelay = m;
}
}

它是:

            // Start MediaPlayer
            mp.start();
            mp.setLooping(true);

            // Get string from ArrayList
            Random randomNumber = new Random();
            selector = randomNumber.nextInt(176);
            // Typewriter animation
            tvQuote.setText("");
            tvQuote.setCharacterDelay(40);
            tvQuote.animateText(listOfQuotes.get(selector));
            mp.release();

除了可能应该是service account

似乎google/cloud取代了'Authorization: Bearer $(gcloud auth application-default print-access-token)' 。对于Translate,您可以编辑translate-v2.json或添加// $cmd = 'gcloud auth application-default login'; $cmd = 'gcloud auth application-default print-access-token'; $token = shell_exec($cmd); ;但是v3beta1除了v2之外还具有其他REST API ...

答案 1 :(得分:0)

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

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

如果您成功消除了所有这些平方,那么您应该很好!

该页面有效地将用户重定向到他们所在的同一页面,但将GET请求的结果包含在url中。响应中包含一个代码,该代码可用于发出另一个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很有帮助。