设为首页收藏本站

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 649|回复: 0

Translating Text Using the Google Translate API and PHP, JSON and cURL

[复制链接]
发表于 2011-11-15 13:23:13 | 显示全部楼层 |阅读模式
Google Translate is a service from Google that you can use to translate text or HTML from one language to another. One of the great features of this service is that they now offer an API to let you programmatically translate text. In this article I will show you how to interact with the Google Translate API.

Initially, the Google Translate API was available only via JavaScript. This has now changed, as version 2 offers a REST interface which returns translations in JSON format.

To use this API you must have a Google API key. More information about this is available at Google Translate V2 Developer Guide.

Note: At time of writing, there is a limit for non-paying customers of 100,000 characters translated per day.
The API at this stage contains three available operations: retrieve a list of available language pairs (languages), translate text (translate), and determine the language of text (detect). In this article I'll show you how to use the translate operation.
All API calls are made to the endpoint https://www.googleapis.com/language/translate/v2.

Input ParametersTo translate text, the following parameters are used:
  • key - This is your Google API key
  • source - The language of the string being translated (e.g. en for English)
  • target - The language you want the text translated to (e.g. es for Spanish)
  • q - The text to translate. This can be HTML code if you're trying to translate a HTML document
If you omit the source parameter, the API will attempt to determine the input language automatically. If you know what language is being used you should specify it so no mistakes are made (especially in cases where short ambigous phrases are being used).
Query LimitsBecause this API is designed to used via a "GET" request, long documents cannot be translated (since there is a character limit for these types of requests).
The good news is that Google allows a way to get around this by "faking" a GET request using a POST request. This is achieved by sending the HTTP header X-HTTP-Method-Override: GET. I will show you how to do this in the code below.
Handling ResultsThe data returned by this API is in JSON format. You can decode this data using the PHP json_decode() function. Once you've converted this response data to a PHP array, you can access the $arr['data']['translations'] key to read the translation data.

Note: This element is an array, since it is possible to translate multiple texts in a single API call (this is achieved by including the q parameter multiple times). This array will contain an element for each translated text.

Another thing to be aware of is that foreign languages will typically use an extended character set. Be sure to handle this correctly.

For instance, if you're translating a HTML, certain characters may not be displayed correctly in the translation if you don't include a header such as
  1. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
复制代码

Translating Text With LanguageTranslatorThe following code is a simple class I created to demonstrate how easy the API is to use. There are some improvements that can be made, as noted at the end of this article, but this is definitely enough to get started.

I've included a number of comments in the code to explain how it works.

Listing 1 A PHP class to translate text using Google Translate (LanguageTranslator.php)
  1. <?php
  2. class LanguageTranslator
  3. {
  4. // this is the API endpoint, as specified by Google
  5. const ENDPOINT = 'https://www.googleapis.com/language/translate/v2';

  6. // holder for you API key, specified when an instance is created
  7. protected $_apiKey;

  8. // constructor, accepts Google API key as its only argument
  9. public function __construct($apiKey)
  10. {
  11. $this->_apiKey = $apiKey;
  12. }

  13. // translate the text/html in $data. Translates to the language
  14. // in $target. Can optionally specify the source language
  15. public function translate($data, $target, $source = '')
  16. {
  17. // this is the form data to be included with the request
  18. $values = array(
  19. 'key' => $this->_apiKey,
  20. 'target' => $target,
  21. 'q' => $data
  22. );

  23. // only include the source data if it's been specified
  24. if (strlen($source) > 0) {
  25. $values['source'] = $source;
  26. }

  27. // turn the form data array into raw format so it can be used with cURL
  28. $formData = http_build_query($values);

  29. // create a connection to the API endpoint
  30. $ch = curl_init(self::ENDPOINT);

  31. // tell cURL to return the response rather than outputting it
  32. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  33. // write the form data to the request in the post body
  34. curl_setopt($ch, CURLOPT_POSTFIELDS, $formData);

  35. // include the header to make Google treat this post request as a get request
  36. curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: GET'));

  37. // execute the HTTP request
  38. $json = curl_exec($ch);
  39. curl_close($ch);

  40. // decode the response data
  41. $data = json_decode($json, true);

  42. // ensure the returned data is valid
  43. if (!is_array($data) || !array_key_exists('data', $data)) {
  44. throw new Exception('Unable to find data key');
  45. }

  46. // ensure the returned data is valid
  47. if (!array_key_exists('translations', $data['data'])) {
  48. throw new Exception('Unable to find translations key');
  49. }

  50. if (!is_array($data['data']['translations'])) {
  51. throw new Exception('Expected array for translations');
  52. }

  53. // loop over the translations and return the first one.
  54. // if you wanted to handle multiple translations in a single call
  55. // you would need to modify how this returns data
  56. foreach ($data['data']['translations'] as $translation) {
  57. return $translation['translatedText'];
  58. }

  59. // assume failure since success would've returned just above
  60. throw new Exception('Translation failed');
  61. }
  62. }
  63. ?>
复制代码

Using the LanguageTranslator Class



The following code shows you can use this class. Be sure to replace the API key and input text as required. This is a crude example that will read English text from a file, translate it to German, then output it to a file.

Listing 2 Making use of the LanguageTranslator class (listing-2.php)
  1. <?php
  2. require_once('LanguageTranslator.php');

  3. $yourApiKey = '';

  4. $sourceData = file_get_contents('/file/to/path.txt');
  5. $source = 'en';

  6. $target = 'de';

  7. $translator = new LanguageTranslator($yourApiKey);

  8. $targetData = $translator->translate($sourceData, $source, $target);
  9. file_put_contents($targetData, 'file.txt-' . $target);
  10. ?>
复制代码

Further Exercises


There are several ways this code can be improved. See if you can make these improvements:
  • Modify the code so multiple texts can be translate in a single call. This is achieved by including the q parameter once for every text. You must then also return all of the corresponding translations.
  • Change the code so it returns the automatically-detected source language if the user did not specify the source language. This is returned in the detectedSourceLanguage value for a given translation.
  • Handle different kinds of errors appropriately. For instance, this code doesn't differentiate between an input error and being over usage quota

By Quentin Zervaas, 6 May 2011
您需要登录后才可以回帖 登录 | 注册

本版积分规则

手机版|小黑屋|BC Morning Website ( Best Deal Inc. 001 )  

GMT-8, 2025-12-12 22:31 , Processed in 0.036055 second(s), 16 queries .

Supported by Best Deal Online X3.5

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表