/deploy/google_translate.php

https://github.com/cclien/coscup2014-website · PHP · 77 lines · 33 code · 13 blank · 31 comment · 2 complexity · dfe7ae69f2921fc720198c3a96d6e980 MD5 · raw file

  1. <?php
  2. /**
  3. The MIT License
  4. Copyright (c) 2011 <Tsung-Hao>
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. *
  21. * @author: Tsung <tsunghao@gmail.com>
  22. */
  23. /**
  24. * API Document: http://code.google.com/intl/zh-TW/apis/language/translate/v2/using_rest.html
  25. * Key: https://code.google.com/apis/console/?api=translate&pli=1
  26. */
  27. # define('TRANSLATE_KEY', 'PUT_YOUR_GOOGLE_API_KEY');
  28. define('TRANSLATE_POST_URL', 'https://www.googleapis.com/language/translate/v2');
  29. function post_url_data($url, $postvar)
  30. {
  31. $ch = curl_init();
  32. curl_setopt($ch, CURLOPT_URL, $url);
  33. curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  34. curl_setopt($ch, CURLOPT_POST, 1);
  35. curl_setopt($ch, CURLOPT_POSTFIELDS, $postvar);
  36. /* Google translate post api need send this header */
  37. curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: GET'));
  38. $res = curl_exec($ch);
  39. curl_close($ch);
  40. return $res;
  41. }
  42. function translate_post($q, $from = 'zh-TW', $to = 'zh-CN')
  43. {
  44. if (empty($q))
  45. return $q;
  46. $arg = array(
  47. 'q' => $q,
  48. 'key' => TRANSLATE_KEY,
  49. 'source' => $from,
  50. 'target' => $to,
  51. );
  52. foreach ($arg as $k => $v)
  53. $postvar[] = $k . '=' . urlencode($v);
  54. $postvar_string = implode("&", $postvar);
  55. $obj = json_decode(post_url_data(TRANSLATE_POST_URL, $postvar_string));
  56. if (isset($obj->error))
  57. return $obj->error->message;
  58. return $obj->data->translations[0]->translatedText;
  59. }
  60. ?>