Home     Publications     Articles and Projects     PhD Thesis     Links    

PHP Client Stub for Microsoft Azure Bing Machine Translation API

Microsoft have deprecated their old translation API and now a different method must be used to access the API via the Azure Marketplace. Of course they give no help to PHP developers with the new API. So here's the PHP client stub ( "wrapper", "abstraction layer" ) that I am now using to access the API. You need to get the client_id and client_secret by registering an app via the Azure Marketplace website.

//New API stub for Microsoft Azure Marketplace Translation API. Bryan McEleney 22/08/2012
function bing_translate($text, $destLang, $srcLang) {

	//App Credentials
	$client_id = "XXXXXXXX";
	$client_secret = "XXXXXXXXX";

	$connection = curl_init();
	curl_setopt($connection, CURLOPT_URL, "http://api.microsofttranslator.com/V2/Ajax.svc/Translate?&from=" . $srcLang . "&to=" . $destLang . "&text=" . urlencode($text));
	curl_setopt($connection, CURLOPT_HEADER, 0);
	curl_setopt($connection, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($connection, CURLOPT_HTTPHEADER, array(azure_bing_translation_get_auth_token($client_id, $client_secret)));
	$str_response = curl_exec($connection);
	$time = microtime(true) * 1000;
	$result = curl_exec($connection);
	$time = microtime(true) * 1000 - $time;

	//echo 'Test result: '.$result."
\n"; //echo 'Test error: '.curl_error($connection)."
\n"; curl_close($connection); //echo 'Connection time (ms): '.$time; return $result; } function azure_bing_translation_get_auth_token($client_id, $client_secret) { $obj_connection = curl_init(); $arr_query_bits = array ( 'grant_type' => 'client_credentials', 'scope' => 'http://api.microsofttranslator.com', 'client_id' => $client_id, 'client_secret' => $client_secret ); $str_query = http_build_query($arr_query_bits); curl_setopt($obj_connection, CURLOPT_URL, 'https://datamarket.accesscontrol.windows.net/v2/OAuth2-13'); curl_setopt($obj_connection, CURLOPT_HEADER, 0); curl_setopt($obj_connection, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($obj_connection, CURLOPT_RETURNTRANSFER, 1); curl_setopt($obj_connection, CURLOPT_POSTFIELDS, $str_query); curl_setopt($obj_connection, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($obj_connection, CURLOPT_POST, TRUE); //print_r('Full token:

'); $token = json_decode (curl_exec($obj_connection)); curl_close($obj_connection); return 'Authorization: Bearer '.$token->{'access_token'}; }