Ad:
 
  • PHP Code Snippet
  • Views: 12155
  • PHP RSS
0

PHP Class for Google AJAX Language API (Language Translation)

by digital-ether on Jan 19th, 2009
This class allows you to use the Google AJAX Translation API to translate arbitrary text to the many languages supported by the Google API.

Source versioning added to:
http://code.google.com/p/php-language-api/
PHP Code Snippet (Toggle Plain Text)
  1. <?php
  2.  
  3. /**
  4.  * Translating language with Google API
  5.  * @author gabe@fijiwebdesign.com
  6.  * @version $id$
  7.  * @license - Share-Alike 3.0 (http://creativecommons.org/licenses/by-sa/3.0/)
  8.  *
  9.  * Google requires attribution for their Language API, please see: http://code.google.com/apis/ajaxlanguage/documentation/#Branding
  10.  *
  11.  */
  12. class Google_Translate_API {
  13.  
  14. /**
  15. * Translate a piece of text with the Google Translate API
  16. * @return String
  17. * @param $text String
  18. * @param $from String[optional] Original language of $text. An empty String will let google decide the language of origin
  19. * @param $to String[optional] Language to translate $text to
  20. */
  21. function translate($text, $from = '', $to = 'en') {
  22. $url = 'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q='.rawurlencode($text).'&langpair='.rawurlencode($from.'|'.$to);
  23. $response = file_get_contents(
  24. $url,
  25. null,
  26. stream_context_create(
  27. array(
  28. 'http'=>array(
  29. 'method'=>"GET",
  30. 'header'=>"Referer: http://".$_SERVER['HTTP_HOST']."/\r\n"
  31. )
  32. )
  33. )
  34. );
  35. if (preg_match("/{\"translatedText\":\"([^\"]+)\"/i", $response, $matches)) {
  36. return self::_unescapeUTF8EscapeSeq($matches[1]);
  37. }
  38. return false;
  39. }
  40.  
  41. /**
  42. * Convert UTF-8 Escape sequences in a string to UTF-8 Bytes
  43. * @return UTF-8 String
  44. * @param $str String
  45. */
  46. function _unescapeUTF8EscapeSeq($str) {
  47. return preg_replace_callback("/\\\u([0-9a-f]{4})/i", create_function('$matches', 'return html_entity_decode(\'&#x\'.$matches[1].\';\', ENT_NOQUOTES, \'UTF-8\');'), $str);
  48. }
  49. }
  50.  
  51. // example usage
  52. $text = 'Welcome to my website.';
  53. $trans_text = Google_Translate_API::translate($text, '', 'it');
  54. if ($trans_text !== false) {
  55. echo $trans_text;
  56. }
  57.  
  58.  
  59. ?>
Comments on this Code Snippet
Message:





About Us | Contact Us | Advertise | Acceptable Use Policy
Build Custom RSS Feed


Follow us on Twitter


© 2010 DaniWeb® LLC