【问题标题】:PHP and Bing Translation APIPHP 和必应翻译 API
【发布时间】:2012-05-31 17:13:25
【问题描述】:

我已在 Azure 市场注册,我有一个客户端 ID 和一个客户端“机密”,但到目前为止我尝试过的所有操作都会导致“400 错误请求”错误。非常感谢!

这是我一直在尝试的一个相当基本的代码示例(我已经编辑了客户端 ID 和秘密值)。我理解 post 变量可以通过 URL 请求传递...我希望这是正确的。

$authURL = 'http://datamarket.accesscontrol.windows.net/v2/OAuth2-13&grant_type=client_credentials&client_id={CLIENT_ID VALUE HERE}&client_secret={CLIENT_SECRET VALUE HERE}&scope=http://api.microsofttranslator.com';
$chpre = curl_init();
curl_setopt($chpre, CURLOPT_URL, $authURL );
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$xpre = curl_exec($chpre);

$texttobetranslated = "الذي تقدمه";
$BingURL = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" . $texttobetranslated . "&from=ar&to=en";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $BingURL );
$x = curl_exec($ch);

【问题讨论】:

  • 嗨,用户,您为什么不向我们展示您所做的工作,然后询问有关代码的具体问题,然后我们可以更好地帮助您。这个网站并不是真正为人们编写代码,而是在他们遇到困难时提供帮助(你是......你只需要发布你的代码:)祝你好运!
  • 是否需要将令牌传递到第二个 curl 请求中? wangpidong.blogspot.com/2012/04/…
  • 我没有注意到,所以谢谢...但添加 $TokenHeader = "Authorization:bearer" 。 $xpre;和 curl_setopt($ch, CURLOPT_HEADER, $TokenHeader);不幸的是没有解决我的问题。
  • 我不确定我能提供多少帮助,但那篇博客文章是相当新的。如果您可以访问 unix 机器(Mac/Linux),我建议您使用自己的值运行他的示例。确保 API 有效并且您的所有密钥都有效,然后这将帮助您判断是您的代码损坏还是您的密钥/令牌。我的想法是缩小问题范围。希望有帮助!
  • 为什么不试试下面的实现code.google.com/p/micrsoft-translator-php-wrapper Demo在renjith.co.in/translate中给出

标签: php translation access-token azure-marketplace


【解决方案1】:

我创建了一个易于使用且易于集成到任何 PHP 项目的小型 PHP 类。你可以找到它here。这是代码:

  <?php
    class BingTranslation
    {
        public $clientID;
        public $clientSecret;

        public function __construct($cid, $secret)
        {
            $this->clientID = $cid;
            $this->clientSecret = $secret;
        }

        public function get_access_token()
        {   
            //if access token is not expired and is stored in COOKIE
            if(isset($_COOKIE['bing_access_token']))
                return $_COOKIE['bing_access_token'];

            // Get a 10-minute access token for Microsoft Translator API.
            $url = 'https://datamarket.accesscontrol.windows.net/v2/OAuth2-13';
            $postParams = 'grant_type=client_credentials&client_id='.urlencode($this->clientID).
            '&client_secret='.urlencode($this->clientSecret).'&scope=http://api.microsofttranslator.com';

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url); 
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postParams);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);  
            $rsp = curl_exec($ch); 
            $rsp = json_decode($rsp);
            $access_token = $rsp->access_token;

            setcookie('bing_access_token', $access_token, $rsp->expires_in);

            return $access_token;
        }

        public function translate($word, $from, $to)
        {
            $access_token = $this->get_access_token();
            $url = 'http://api.microsofttranslator.com/V2/Http.svc/Translate?text='.$word.'&from='.$from.'&to='.$to;

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url); 
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization:bearer '.$access_token));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);  
            $rsp = curl_exec($ch); 

            preg_match_all('/<string (.*?)>(.*?)<\/string>/s', $rsp, $matches);

            return $matches[2][0];
        }

        public function translate2($word, $from, $tos)
        {
            //translates 1 word to several languages
            //$tos is array of languages to translate to
            //returns array of translations as $result['en']=>'Hello'

            $access_token = $this->get_access_token();

            $result[$from] = $word;

            foreach($tos as $to)
            {
                $url = 'http://api.microsofttranslator.com/V2/Http.svc/Translate?text=hello&from='.$from.'&to='.$to;

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url); 
                curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization:bearer '.$access_token));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);  
                $rsp = curl_exec($ch); 

                preg_match_all('/<string (.*?)>(.*?)<\/string>/s', $rsp, $matches);

                $result[$to] = $matches[2][0];
            }

            return $result;
        }
    }
 ?>

【讨论】:

    【解决方案2】:

    请将此代码放在您的标题部分.. 这对我来说是完美的..享受它

    <div id='MicrosoftTranslatorWidget' class='Light' style='color:white;background-color:#555555'></div>
    <script type='text/javascript'>
    setTimeout(function(){{
    var s=document.createElement('script');
    s.type='text/javascript';
    s.charset='UTF-8';
    s.src=((location && location.href && location.href.indexOf('https') == 0)?'https://ssl.microsofttranslator.com':'http://www.microsofttranslator.com')+'/ajax/v3/WidgetV3.ashx?siteData=ueOIGRSKkd965FeEGM5JtQ**&ctf=False&ui=true&settings=Manual&from=';
    var p=document.getElementsByTagName('head')[0]||document.documentElement;
    p.insertBefore(s,p.firstChild); 
    }},0);
    </script>
    

    【讨论】:

      【解决方案3】:

      以下是基于必应翻译 API 的最新凭据为我工作的最新代码:

      <?php 
      $key1 = "??????";  //enter your azure key here
      $endpoint = 'https://languagetranslationservice.cognitiveservices.azure.com/sts/v1.0/issuetoken';  //enter your azure end point here
      $from = "en";  //Support Languages: https://docs.microsoft.com/en-us/azure/cognitive-services/translator/language-support
      $to = "te";
      $inputStr = "welcome to paradise";
      
      function getToken($key1, $endpoint)
      {
          $ch = curl_init();
          $data_string = json_encode('{body}');
          curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
          curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                  'Content-Type: application/json',
                  'Content-Length: ' . strlen($data_string),
                  'Ocp-Apim-Subscription-Key: ' . $key1
              )
          );
          curl_setopt($ch, CURLOPT_URL, $endpoint);
          curl_setopt($ch, CURLOPT_HEADER, false);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
          $strResponse = curl_exec($ch);
          curl_close($ch);
          return $strResponse;
      }
      
      // function for translation
      function curlRequest($url)
      {
          $ch = curl_init();
          curl_setopt($ch, CURLOPT_URL, $url);
          curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
          $curlResponse = curl_exec($ch);
          curl_close($ch);
          return $curlResponse;
      }
      
      //start translation
      $accessToken = getToken($key1, $endpoint);
      $params = "text=" . urlencode($inputStr) . "&to=" . $to . "&from=" . $from . "&appId=Bearer+" . $accessToken;
      $translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate?$params";
      $curlResponse = curlRequest($translateUrl);
      $output = simplexml_load_string($curlResponse);
      echo $output;
      ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-06
        • 1970-01-01
        • 2012-01-26
        相关资源
        最近更新 更多