通过PHP使用Google Translate API
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 codecurl_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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 视频编码解码(H264中的profile
- 下一篇: python汉语叫什么意思_Python