Guest User

Untitled

a guest
Jan 21st, 2017
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.54 KB | None | 0 0
  1. <?php
  2.  
  3. $your_client_id = '0750facb-bb29-43b4-a629-42603c2efbea';
  4. $your_secret = 'I3GDuMftmn4pTeUTiJgJp0VGNbEkfDbBgwFDC7eb6E0';
  5.  
  6.  
  7.  
  8. class BingTranslation
  9. {
  10. public $clientID;
  11. public $clientSecret;
  12.  
  13. public function __construct($cid, $secret)
  14. {
  15. $this->clientID = $cid;
  16. $this->clientSecret = $secret;
  17. }
  18.  
  19. public function get_access_token()
  20. {
  21. //if access token is not expired and is stored in COOKIE
  22. if(isset($_COOKIE['bing_access_token']))
  23. return $_COOKIE['bing_access_token'];
  24.  
  25. // Get a 10-minute access token for Microsoft Translator API.
  26. $url = 'https://datamarket.accesscontrol.windows.net/v2/OAuth2-13';
  27. $postParams = 'grant_type=client_credentials&client_id='.urlencode($this->clientID).
  28. '&client_secret='.urlencode($this->clientSecret).'&scope=http://api.microsofttranslator.com';
  29.  
  30. $ch = curl_init();
  31. curl_setopt($ch, CURLOPT_URL, $url);
  32. curl_setopt($ch, CURLOPT_POSTFIELDS, $postParams);
  33. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  34. $rsp = curl_exec($ch);
  35. $rsp = json_decode($rsp);
  36. $access_token = $rsp->access_token;
  37.  
  38. setcookie('bing_access_token', $access_token, $rsp->expires_in);
  39.  
  40. return $access_token;
  41. }
  42.  
  43.  
  44. public function translate($word, $from, $to)
  45. {
  46. $access_token = $this->get_access_token();
  47. $url = 'http://api.microsofttranslator.com/V2/Http.svc/Translate?text='.$word.'&from='.$from.'&to='.$to;
  48.  
  49. $ch = curl_init();
  50. curl_setopt($ch, CURLOPT_URL, $url);
  51. curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization:bearer '.$access_token));
  52. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  53. $rsp = curl_exec($ch);
  54.  
  55. preg_match_all('/<string (.*?)>(.*?)</string>/s', $rsp, $matches);
  56. return $matches[2][0];
  57. }
  58. }
  59.  
  60.  
  61. //usage example
  62. $bt = new BingTranslation($your_client_id, $your_secret);
  63. echo $bt->translate('home', 'en', 'ru');
  64. ?>
  65.  
  66. GET /V2/Http.svc/Translate?text=привет мир&from=ru&to=en HTTP/1.1
  67.  
  68. $url = 'http://api.microsofttranslator.com/V2/Http.svc/Translate?text='.urlencode($word).'&from='.urlencode($from).'&to='.urlencode($to);
  69.  
  70. $url = 'http://api.microsofttranslator.com/V2/Http.svc/Translate?'.http_build_query([
  71. 'text' => $word,
  72. 'from' => $from,
  73. 'to' => $to,
  74. ]);
Add Comment
Please, Sign In to add comment