PHP and Bing Translation API

18.3k views Asked by At

I've registered with Azure Marketplace, I have a client ID and a client "secret", but everything I've tried so far nonetheless results in a "400 Bad Request" error. Thanks very much!

Here is a rather basic sample of the code I've been trying (I've redacted the Client ID and Secret Value). I'm operating with the understanding that the post variables can be passed through the URL request... I hope that's correct.

$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);
3

There are 3 answers

0
torayeff On

I have createde little PHP class that is easy to use and easy to integrate to any PHP project. You can find it here. This is code:

  <?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;
        }
    }
 ?>
0
user3447328 On

Please Put this code at your header part.. This Works Perfect For Me..Enjoy it

<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>
0
Murali Krishna M. On

Here is the latest code that is working for me based on latest credentials from Bing Translation 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://learn.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;
?>