Note: an advanced continuation of this topic is accessible here

注意:可在此处访问该主题的高级继续

If your site serves visitors from different countries, you may already have translated all its static content into several languages. But what to do with the content posted daily by the users in comments, opinions and ratings? As this may be as valuable a part of your site as the static content, you should think of finding a way to translate it into other languages. One service that can help is, of course, Google Translate.

如果您的网站为来自不同国家/地区的访问者提供服务,则您可能已经将其所有静态内容翻译成多种语言。 但是,用户每天在评论,意见和评分中发布的内容该怎么办? 由于这可能与静态内容一样对您的网站有价值,因此您应该考虑寻找一种将其翻译成其他语言的方法。 当然,可以提供帮助的一项服务是Google Translate 。

After going through this tutorial you will be able to fetch translations from the Google Translate API right from your app. You will learn how to gain access to the API, how to use it and how to handle errors if they occur.

阅读完本教程后,您将可以直接从您的应用程序从Google Translate API获取翻译。 您将学习如何获得对API的访问权,如何使用它以及如何处理发生的错误。

创建一个Google API帐户 (Creating a Google API account)

In order to gain access to the Google Translate API, you will have to create a new project on the Google APIs Console which requires an active Google account. After creating a new project, just turn on Translate API on the list of all the available APIs by flicking a switch.

为了获得对Google Translate API的访问权,您将必须在Google API控制台上创建一个新项目,该项目需要一个有效的Google帐户。 创建新项目后,只需轻按一下开关即可打开所有可用API列表上的Translate API。

价钱 (Pricing)

Since the Google Translate API is a paid service, you will also need to enable billing in your project settings. To do so, click Billing in the left menu on the Google APIs Console and then Enable billing. You will be asked to enter the payment data such as your address and credit card number. Different payment options are available in various countries but credit card payment should be recognised worldwide.

由于Google Translate API是一项付费服务 ,因此您还需要在项目设置中启用结算功能。 要做到这一点,请单击在谷歌API控制台左侧菜单中选择结算 ,然后启用计费 。 系统将要求您输入付款数据,例如您的地址和信用卡号。 各个国家/地区提供不同的付款方式,但信用卡付款应在全球范围内得到认可。

At the time of writing this article, the usage fee was $20 per 1 million characters of translation or language detection. Which means that translating a user comment of 300-400 characters would cost you $0.006 – $0.008. Naturally, if you want to translate a text into more than one target language, you will have to pay separately for each translation.

在撰写本文时,使用费为每100万个翻译或语言检测字符20美元。 这意味着翻译一个300-400个字符的用户注释将花费您$ 0.006-$ 0.008。 自然地,如果您想将一种文本翻译成一种以上的目标语言,则必须为每种翻译单独付费。

If you fear getting billed too much for the translations you make, you can control the API usage in your project by setting the maximum limit of characters that can be translated daily. The entire configuration is available on the Google APIs Console.

如果您担心因翻译而收取过多费用,则可以通过设置每天可以翻译的最大字符数来控制项目中的API使用。 整个配置可在Google API控制台上找到。

获取API密钥 (Getting the API key)

To access the Translate API from your app, you will need an API key connected to the project you have created on the Google APIs Console. To get the API key, just click API Access in the menu at the Google API Console page. You will find the key you need under Simple API access.

要从您的应用访问Translate API,您需要将API密钥连接到您在Google API控制台上创建的项目。 要获取API密钥,只需在Google API控制台页面的菜单中单击API访问 。 您将在“ 简单API访问”下找到所需的密钥。

从您的应用访问Translate API (Accessing Translate API from your app)

The Translate API offers 3 methods: – translate, which translates the given text from one language to another, – detect, which detects the language of the given text, – languages, which lists the source and target languages supported by the API.

Translate API提供了3种方法:– translation ,将给定文本从一种语言翻译为另一种语言; – detect ,检测给定文本的语言; – language ,列出API支持的源语言和目标语言。

All the methods are called via GET requests. A common way of making such a request in PHP is to use the cURL library, which we will use in the examples below. The parameters passed to each method need to be URL encoded which may be achieved in PHP using the rawurlencode() function. Remember that in each call you have to pass your API key as a key parameter.

所有方法都是通过GET请求调用的。 在PHP中发出此类请求的一种常见方式是使用cURL库 ,我们将在以下示例中使用该库 。 传递给每种方法的参数需要进行URL编码,这可以在PHP中使用rawurlencode()函数来实现。 请记住,在每次调用中,您都必须传递API密钥作为密钥参数。

The results of each Google Translate API method are returned as a string representing a JSON object. To parse it, we will use the json_decode() function.

每个Google Translate API方法的结果都以代表JSON对象的字符串形式返回。 为了解析它,我们将使用json_decode()函数。

样品要求 (Sample request)

Translate and detect services are paid but we can use the third method – languages – just to check if our app can connect with the API. To do so, we will make a request to the following URL: https://www.googleapis.com/language/translate/v2/languages

翻译检测服务是付费的,但是我们可以使用第三种方法- 语言 -仅检查我们的应用程序是否可以与API连接。 为此,我们将请求以下网址: https://www.googleapis.com/language/translate/v2/languages : https://www.googleapis.com/language/translate/v2/languages

The entire code looks as follows:

整个代码如下所示:

<?php
$apiKey = '<paste your API key here>';
$url = 'https://www.googleapis.com/language/translate/v2/languages?key=' . $apiKey;
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);     //We want the result to be saved into variable, not printed out
$response = curl_exec($handle);
curl_close($handle);
print_r(json_decode($response, true));
?>

After executing the code above, you should see an array of all the languages that can be processed by the Google Translate API. A similar table is available in the documentation. It is important to browse through that table because you will need to include language codes stated there when submitting a request for translating a specific text.

执行完以上代码后,您应该会看到Google Translate API可以处理的所有语言的数组。 文档中提供了类似的表格。 浏览该表很重要,因为在提交翻译特定文本的请求时,您将需要包括在其中列出的语言代码。

获取翻译 (Getting the translations)

The core functionality of the Google Translate API is available through its translate method. It is accessible under the following URL: https://www.googleapis.com/language/translate/v2

Google Translate API的核心功能可通过其translation方法获得。 可通过以下URL访问: https://www.googleapis.com/language/translate/v2 : https://www.googleapis.com/language/translate/v2

The translate method has several parameters. The most important are: – q – the input text, – source – the source language (if it's not specified, Google will try to identify it automatically), – target – the target language

平移方法有几个参数。 最重要的是:– q –输入文本,– –源语言(如果未指定,Google会尝试自动识别它),– 目标 –目标语言

If you want to get a translated text, you have to change the URL of the request from the previous example. The rest of the code looks very similar:

如果要获取翻译的文本,则必须更改上一个示例中的请求的URL。 其余代码看起来非常相似:

<?php
$apiKey = '<paste your API key here>';
$text = 'Hello world!';
$url = 'https://www.googleapis.com/language/translate/v2?key=' . $apiKey . '&q=' . rawurlencode($text) . '&source=en&target=fr';
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($handle);
$responseDecoded = json_decode($response, true);
curl_close($handle);
echo 'Source: ' . $text . '<br>';
echo 'Translation: ' . $responseDecoded['data']['translations'][0]['translatedText'];
?>

A sample response containing the translated text looks as follows:

包含已翻译文本的示例响应如下所示:

{
"data": {
"translations": [{"translatedText": "Bonjour tout le monde!"}]
}
}

如果不设置源语言会怎样? (What happens if you don't set the source language?)

If you decide not to include the source language (the source parameter) in the request, two scenarios can happen: 1. Google will manage to detect the language by itself, the JSON response will consequently contain an additional detectedSourceLanguage property holding the source language code. 2. The source language will not be successfully detected (e.g. when the source text was too short) and the Google Translate API will return an HTTP 500 error. This leads to the next part of the tutorial – handling errors.

如果您决定在请求中不包括源语言( source参数),则可能发生两种情况:1. Google将设法自行检测语言,因此JSON响应将包含一个额外的detectedSourceLanguage属性,该属性保存源语言代码。 2.无法成功检测到源语言(例如,当源文本太短时),并且Google Translate API将返回HTTP 500错误。 这导致了本教程的下一部分–处理错误。

处理错误 (Handling errors)

When your request cannot be processed, the Google Translate API returns an HTTP response with a code representing the type of the error. After executing a request using cURL, you can get the server response code using the curl_getinfo() function. If the response code is different than 200, it means that something went wrong.

当您的请求无法处理时,Google Translate API会返回HTTP响应,其中包含代表错误类型的代码。 使用cURL执行请求后,可以使用curl_getinfo()函数获取服务器响应代码。 如果响应代码不同于200 ,则表示出了点问题。

The Google Translate API can return following error codes: – 400 (Bad request) – your request is missing some parameters or you have passed wrong values to the parameters present in the request (e.g. an invalid language code), – 403 (Forbidden) – you have entered an incorrect API key or have exceeded your quota, – 500 (Internal Server Error) – Google cannot identify the source language of your text or another error occurred.

Google Translate API可以返回以下错误代码:– 400(错误请求) –您的请求缺少某些参数,或者您为请求中存在的参数传递了错误的值(例如无效的语言代码),– 403(禁止) –您输入了错误的API密钥或超出了配额,– 500(内部服务器错误) – Google无法识别您的文本的源语言或发生了另一个错误。

Additionally, when an error occurs, the Google Translate API returns a JSON response containing an error description. For example, when one of the required parameters is missing, the server will reply with a following response:

此外,发生错误时,Google Translate API会返回一个包含错误描述的JSON响应。 例如,当缺少必需参数之一时,服务器将回复以下响应:

{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Required parameter: target",
"locationType": "parameter",
"location": "target"
}
],
"code": 400,
"message": "Required parameter: target"
}
}

So the best way of handling errors when querying the Google Translate API service is just to combine checking the HTTP response code and parsing the JSON response from the server. What is important, curl_getinfo() must be called before curl_close():

因此,查询Google Translate API服务时处理错误的最好方法就是将检查HTTP响应代码和解析来自服务器的JSON响应结合在一起。 什么是重要的,curl_getinfo()必须curl_close之前调用():

<?php
$apiKey = '<paste your API key here>';
$text = 'Hello world!';
$url = 'https://www.googleapis.com/language/translate/v2?key=' . $apiKey . '&q=' . rawurlencode($text) . '&source=en&target=fr';
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($handle);
$responseDecoded = json_decode($response, true);
$responseCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);      //Here we fetch the HTTP response code
curl_close($handle);
if($responseCode != 200) {
echo 'Fetching translation failed! Server response code:' . $responseCode . '<br>';
echo 'Error description: ' . $responseDecoded['error']['errors'][0]['message'];
}
else {
echo 'Source: ' . $text . '<br>';
echo 'Translation: ' . $responseDecoded['data']['translations'][0]['translatedText'];
}
?>

一个请求中提供多种翻译 (Multiple translations in one request)

You can translate several texts in one request, which is undoubtedly more efficient than executing separate request for each translation. To do so, just pass a couple of q parameters, each containing one text to translate.

您可以在一个请求中翻译多个文本,这无疑比对每个翻译执行单独的请求更有效。 为此,只需传递几个q参数,每个参数包含一个要翻译的文本。

However, it gets a little tricky here: – if your source texts are all of the same language, you can pass the source parameter containing the language code of all the texts; – but if you want to translate a couple of texts in different languages, you cannot pass several source parameters. In such case you have to omit the source parameter and just let Google guess what the languages of the source texts are.

但是,这里有些麻烦:–如果源文本都是相同的语言,则可以传递包含所有文本的语言代码的source参数; –但是,如果您要翻译几种不同语言的文本,则不能传递多个参数。 在这种情况下,您必须省略source参数,而只是让Google猜测源文本的语言。

Also note that you cannot get multiple translations of one source text in a single request. If you want to translate one text to different target languages, you have to make separate requests.

另请注意,您无法在单个请求中获得一个源文本的多种翻译。 如果要将一种文本翻译成不同的目标语言,则必须提出单独的请求。

结论 (Conclusion)

Now you know the basics of connecting your app to the Google Translate API. More complicated implementations of the API may include auto-fetching translations when a user submits some content (or when a site admin approves it) and saving translations to a database. We'll cover such advanced examples in a future article (part 2 here).

现在,您已经知道了将应用程序连接到Google Translate API的基本知识。 API的更复杂的实现可能包括在用户提交某些内容时(或在网站管理员批准时)自动获取翻译,并将翻译保存到数据库中。 我们将在以后的文章( 此处第2部分)中介绍此类高级示例。

If you plan to use the Google Translate API in your app, please remember to read the Terms of service and Attribution requirements which contain several guidelines on how to display the translated content on a webpage.

如果您打算在应用程序中使用Google Translate API,请记住阅读服务条款和归因要求 ,其中包含有关如何在网页上显示翻译后内容的几条准则。

If you have any questions or comments regarding the article, feel free to post a comment below or contact me through Google+.

如果您对本文有任何疑问或评论,请随时在下面发表评论,或通过Google+与我联系。

翻译自: https://www.sitepoint.com/using-google-translate-api-php/

通过PHP使用Google Translate API相关推荐

  1. Google Translate API

    Google Translate API 近期在做的一个任务,但是网上的资料甚少,经过了几番波折,终于弄好了.实现过程很简单,拿出来共享一下,免得大家像我一样找了半天. 谷歌翻译升级到2.0后变为收费 ...

  2. Goslate: Free Google Translate API

    Python爬虫视频教程零基础小白到scrapy爬虫高手-轻松入门 https://item.taobao.com/item.htm?spm=a1z38n.10677092.0.0.482434a6E ...

  3. python 调用Google Translate API进行翻译

    调用Google 翻译API进行翻译 #!/usr/bin/python #coding: UTF-8 import sys reload(sys) sys.setdefaultencoding('u ...

  4. 如何用google translate API接口

    rootsoso 最近要做一个要用到翻译功能的插件,很自然就想到了利用 google translate 的强大,但是 google 之开放了 ajax 的 api ,没有开放语言的接口.这也不难,通 ...

  5. python调用谷歌翻译英文文献pdf_Python 调用 Google Translate API 批量翻译文章

    有时候批量翻译中文文章,批量变成各个小语种的语言,手动的粘贴复制是非常慢的.需要调用翻译 API 接口,综合对比市面上的各个翻译 API,个人觉得 Google 的翻译 API 最为好用和准确. 下面 ...

  6. 教你找到免费的Google Translate API(谷歌翻译接口)+C#版的Google翻译函数

    http://www.crifan.com/teach_you_how_to_find_free_google_translate_api/ (还没试过有时间试下.....) 今日,在想要在C#中,利 ...

  7. python 调用Google Translate API 翻译

    1.安装相关模块 pip install --upgrade google-cloud 或者 pip install --upgrade google-cloud-translate 2.调用api进 ...

  8. python调用google translate API(谷歌翻译) 的使用方法-手动构造HTTP 请求模式

    这个页面中手动的填写请求参数之后,包括目标语言,源语言,输入的字符,目标格式等,可以得到翻译输出,如下图所示: 可以看到本质上是向服务器发起一个post请求,然后服务器在response中将翻译结果返 ...

  9. 借助Google Translate API实现网站多国语言翻译功能

    功能很简单,之前在做项目时用到的,现在分享出来.先看下效果吧: 中文 | 英文 电锯惊魂2.3.4导演达伦斯·鲍斯曼的新片<母亲节>已经出下载了,此片翻拍1980年的恐怖片经典<Mo ...

  10. 谷歌翻译 google translation api

    以下任何一个实例均可实现谷歌翻译功能: 实例 1: <?phpfunction translate( $text, $destLang = 'zh-cn', $srcLang = 'en' ) ...

最新文章

  1. 亚信安全服务器深度安全防护系统中标“世界最长”的城轨网络
  2. linux rpm目录,Linux修改RPM的安装目录的方法
  3. 放张载玻片就能放大一万倍,普通光学显微镜都馋哭了 | Nature子刊
  4. 基于Python——实现远程下载sftp文件(只下载.zip文件)
  5. Facebook:苹果谷歌支持HTML5会死啊
  6. QEMU 3.0.0 新特性一览
  7. (转)C#开发微信门户及应用(5)--用户分组信息管理
  8. testflight怎么做版本更新_《动物森友会》万圣节版本更新后,别忘了做这五件事情...
  9. 屋子里有1到100号100盏关闭的灯
  10. 构建postfix邮件服务器(五)extmail和extman的安装,实现web使用和管理邮件系统...
  11. python抢商品_python爬虫,抢小米抢购,
  12. 远程连接工具Putty 相关
  13. 最新中国数据中心排行榜
  14. 小米手机扩容教程_小米笔记本硬盘扩容教程:5分钟搞定,存储容量瞬间翻倍...
  15. 12点转成0点(原因时间格式化为十二小时制导致)
  16. 调用泛微OA接口的一些基本常识
  17. 解决ERROR: distribution port 25672 in use by another node: rabbit@
  18. TLE8242-2L的开关/比例电磁阀驱动电路
  19. 计算机教资科目三书籍,【教资笔试科目三】数学学科复习指导
  20. 解决com.mchange.v2.c3p0.DriverManagerDataSource. Could not load driverClass com.mysql.cj.jdbc.Driver报错

热门文章

  1. 【物联网+GIS】让传感器数据在三维地图上显示,更直观,更震撼!
  2. 抓取lol全英雄图(不含皮肤)
  3. Pytorch求向量的L1范数或L2范数
  4. 应用程序错误电脑黑屏_werfault应用程序错误黑屏|Win7解决werfault.exe应用程序错误方法...
  5. 谷歌邮箱无法登录问题
  6. python数据分析09_pandas数据聚合与分组运算
  7. 个人整理的免费的Bootstrap模板
  8. Hadoop1.0和2.0的主要区别
  9. http代表的是什么?http代表的是什么意思
  10. 处理 JS中 undefined 的7个技巧