Get Multiple Translations using Microsoft Translator API - php

I would like to get multiple poosible translations for a given word using the /getTranslations method from the Microsoft Translator API according to the API reference. Unfortunately, the provided example on github is outdated: Outdated Example. I did manage to update the getTokens function and references to it, and I did get a translation back, but I need multiple.
Does anyone have a working example/know a fix to my code?
Here is my code:
<?php
class AccessTokenAuthentication {
/*
* Get the access token.
*
* #param string $grantType Grant type.
* #param string $scopeUrl Application Scope URL.
* #param string $clientID Application client ID.
* #param string $clientSecret Application client ID.
* #param string $authUrl Oauth Url.
*
* #return string.
*/
function getToken($azure_key)
{
$url = 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken';
$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: ' . $azure_key
)
);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$strResponse = curl_exec($ch);
curl_close($ch);
return $strResponse;
}
}
/*
* Class:HTTPTranslator
*
* Processing the translator request.
*/
Class HTTPTranslator {
/*
* Create and execute the HTTP CURL request.
*
* #param string $url HTTP Url.
* #param string $authHeader Authorization Header string.
*
* #return string.
*
*/
function curlRequest($url, $authHeader) {
//Initialize the Curl Session.
$ch = curl_init();
//Set the Curl url.
curl_setopt ($ch, CURLOPT_URL, $url);
//Set the HTTP HEADER Fields.
curl_setopt ($ch, CURLOPT_HTTPHEADER, array($authHeader,"Content-Type: text/xml", 'Content-Length: 0'));
//CURLOPT_RETURNTRANSFER- TRUE to return the transfer as a string of the return value of curl_exec().
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
//CURLOPT_SSL_VERIFYPEER- Set FALSE to stop cURL from verifying the peer's certificate.
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, False);
//Set HTTP POST Request.
curl_setopt($ch, CURLOPT_POST, TRUE);
//Execute the cURL session.
$curlResponse = curl_exec($ch);
//Get the Error Code returned by Curl.
$curlErrno = curl_errno($ch);
if ($curlErrno) {
$curlError = curl_error($ch);
throw new Exception($curlError);
}
//Close a cURL session.
curl_close($ch);
return $curlResponse;
}
}
try {
//Azure Key
$azure_key = "<my key>";
//Client ID of the application.
//$clientID = "clientId";
//Client Secret key of the application.
//$clientSecret = "ClientSecret";
//OAuth Url.
$authUrl = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/";
//Application Scope Url
//$scopeUrl = "http://api.microsofttranslator.com";
//Application grant type
//$grantType = "client_credentials";
//Create the AccessTokenAuthentication object.
$authObj = new AccessTokenAuthentication();
//Get the Access token.
$accessToken = $authObj->getToken($azure_key);
//Create the authorization Header string.
$authHeader = "Authorization: Bearer ". $accessToken;
//Set the Params.
$inputStr = "get";
$fromLanguage = "en";
$toLanguage = "de";
//$user = 'TestUser';
$category = "general";
//$uri = null;
$contentType = "text/plain";
$maxTranslation = 5;
//Create the string for passing the values through GET method.
$params = "from=$fromLanguage".
"&to=$toLanguage".
"&maxTranslations=$maxTranslation".
"&text=".urlencode($inputStr).
//"&user=$user".
//"&uri=$uri".
"&contentType=$contentType";
//HTTP getTranslationsMethod URL.
$getTranslationUrl = "http://api.microsofttranslator.com/V2/Http.svc/GetTranslations?$params";
//Create the Translator Object.
$translatorObj = new HTTPTranslator();
//Call the curlRequest.
$curlResponse = $translatorObj->curlRequest($getTranslationUrl, $authHeader);
//Interprets a string of XML into an object.
$xmlObj = simplexml_load_string($curlResponse);
$translationObj = $xmlObj->Translations;
$translationMatchArr = $translationObj->TranslationMatch;
print_r($translationMatchArr);
echo "Get Translation For <b>$inputStr</b>";
echo "<table border ='2px'>";
echo "<tr><td><b>Count</b></td><td><b>MatchDegree</b></td>
<td><b>Rating</b></td><td><b>TranslatedText</b></td></tr>";
foreach($translationMatchArr as $translationMatch) {
echo "<tr><td>$translationMatch->Count</td><td>$translationMatch->MatchDegree</td><td>$translationMatch->Rating</td>
<td>$translationMatch->TranslatedText</td></tr>";
}
echo "</table></br>";
} catch (Exception $e) {
echo "Exception: " . $e->getMessage() . PHP_EOL;
}

I solved the problem this way:
(IncludeMultipleMTAlternatives mast be first in options section)
<GetTranslationsArrayRequest>
<AppId></AppId>
<From>en</From>
<Options>
<IncludeMultipleMTAlternatives xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2">true</IncludeMultipleMTAlternatives>
<State xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2">777</State>
</Options>
<Texts>
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">world</string>
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">sun</string>
</Texts>
<To>ru</To>
<MaxTranslations>10</MaxTranslations>
</GetTranslationsArrayRequest>

The GetTranslations() and GetTranslationsArray() methods in the V2 API of Microsoft Translator include an optional Boolean flag "IncludeMultipleMTAlternatives".
The method will return up to maxTranslations alternatives, even if there are not as many CTF entries available, where the delta is supplied from the n-best list of the translator engine. The machine-generated alternatives are returned with a rating of 0. The human-curated alternatives will have a rating of 1 or higher.

Related

How can I get an Authentication Token for Microsoft Translator API?

I want to get an Authentication Token for the Microsoft Translator API. This is my code:
<?php
//1. initialize cURL
$ch = curl_init();
//2. set options
//Set to POST request
curl_setopt($ch, CURLOPT_POST,1);
// URL to send the request to
curl_setopt($ch, CURLOPT_URL, 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken');
//return instead of outputting directly
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//whether to include header in the output. here set to false
curl_setopt($ch, CURLOPT_HEADER, 0);
//pass my subscription key
curl_setopt($ch, CURLOPT_POSTFIELDS,array(Subscription-Key => '<my-key>'));
//CURLOPT_SSL_VERIFYPEER- Set to false to stop verifying certificate
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//3. Execute the request and fetch the response. check for errors
$output = curl_exec($ch);
if ($output === FALSE) {
echo "cURL Error" . curl_error($ch);
}
//4. close and free up the curl handle
curl_close($ch);
//5. display raw output
print_r($output);
?>
it gives me the following error:
{ "statusCode": 401, "message": "Access denied due to missing subscription key. Make sure to include subscription key when making requests to an API." }
which could mean that the key is invalid according to the website below, but I ensured the key is valid on the same website.
http://docs.microsofttranslator.com/oauth-token.html
I did find some examples online on how to get the Authenticationtoken, but they are outdated.
How can I get the AuthenticationToken/achieve that microsoft recognises my key?
You're passing the subscription-key wrong -
The subscription key should passed in the header (Ocp-Apim-Subscription-Key) or as a querystring parameter in the URL ?Subscription-Key=
And you should use Key1 or Key2 generated by the Azure cognitive service dashboard.
FYI - M$ has made a token generator available for testing purposes, this should give you a clue which keys are used for which purpose:
http://docs.microsofttranslator.com/oauth-token.html
Here's a working PHP script which translates a string from EN to FR (it's based on an outdated WP plugin called Wp-Slug-Translate by BoLiQuan which I've modified for this purpose):
<?php
define("CLIENTID",'<client-name>'); // client name/id
define("CLIENTSECRET",'<client-key>'); // Put key1 or key 2 here
define("SOURCE","en");
define("TARGET","fr");
class WstHttpRequest
{
function curlRequest($url, $header = array(), $postData = ''){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if(!empty($header)){
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
if(!empty($postData)){
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($postData) ? http_build_query($postData) : $postData);
}
$curlResponse = curl_exec($ch);
curl_close($ch);
return $curlResponse;
}
}
class WstMicrosoftTranslator extends WstHttpRequest
{
private $_clientID = CLIENTID;
private $_clientSecret = CLIENTSECRET;
private $_fromLanguage = SOURCE;
private $_toLanguage = TARGET;
private $_grantType = "client_credentials";
private $_scopeUrl = "http://api.microsofttranslator.com";
private $_authUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
// added subscription-key
private function _getTokens(){
try{
$header = array('Ocp-Apim-Subscription-Key: '.$this->_clientSecret);
$postData = array(
'grant_type' => $this->_grantType,
'scope' => $this->_scopeUrl,
'client_id' => $this->_clientID,
'client_secret' => $this->_clientSecret
);
$response = $this->curlRequest($this->_authUrl, $header, $postData);
if (!empty($response))
return $response;
}
catch(Exception $e){
echo "Exception-" . $e->getMessage();
}
}
function translate($inputStr){
$params = "text=" . rawurlencode($inputStr) . "&from=" . $this->_fromLanguage . "&to=" . $this->_toLanguage;
$translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate?$params";
$accessToken = $this->_getTokens();
$authHeader = "Authorization: Bearer " . $accessToken;
$header = array($authHeader, "Content-Type: text/xml");
$curlResponse = $this->curlRequest($translateUrl, $header);
$xmlObj = simplexml_load_string($curlResponse);
$translatedStr = '';
foreach((array)$xmlObj[0] as $val){
$translatedStr = $val;
}
return $translatedStr;
}
}
function bing_translator($string) {
$wst_microsoft= new WstMicrosoftTranslator();
return $wst_microsoft->translate($string);
}
echo bing_translator("How about translating this?");
?>
Add your key also in the URL.
curl_setopt($ch, CURLOPT_URL, 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken?Subscription-Key={your key}');
But leave it also in the CURLOPT_POSTFIELDS.

PHP CURL Get request with uri containing dollar sign returns 400 Bad Request

I am trying to use the ChannelAdvisor REST API in PHP to load a list of stock levels that changed since the last sync. This process is documented here: http://developers.channeladvisor.com/rest/#946
Based on the documentation, I have ran a test in Post Man (chrome rest client) to make sure It's working as intended & it does:
Since the test was successfully, I started to work on the PHP script to interact with the REST API in the same manner and it's not quite working correctly. I am getting the following output:
Bad Request - HTTP Error 400. The request is badly formed.
This is my script so far (I am working with Laravel 4, but it's unrelated to that). The issue is with the curlGET method:
<?php namespace Latheesan\ThirdParty\ChannelAdvisorREST;
class ChannelAdvisorREST {
/**
* ChannelAdvisor base uri
*/
const BASE_URL = 'https://api.channeladvisor.com';
/**
* ChannelAdvisor config data
*/
private $config;
/**
* Class constructor
*/
public function __construct()
{
$this->config = \Config::get('channeladvisor');
}
/**
* Method to load stock updates since last sync.
*
* #param $accountId
* #param $lastSync
* #return array
*/
public function getStockUpdates($accountId, $lastSync)
{
// Anticipate errors
try
{
// Init
$stockUpdates = [];
// Query channel advisor
$stockUpdateResults = self::curlGET($accountId, '/v1/Products?$filter=QuantityUpdateDateUtc gt '. $lastSync);
// TODO: parse $stockUpdateResults into $stockUpdates
// Success
return $this->successResponse($stockUpdateResults);
}
catch (\Exception $ex)
{
// Error response
return $this->errorResponse('Failed to load stock updates - '. $ex->getMessage());
}
}
/**
* Generic method to output error responses.
*
* #param string $message
* #return array
*/
private function errorResponse($message = '')
{
// Error
return [
'IsError' => true,
'ErrorMsg' => $message,
'Data' => ''
];
}
/**
* Generic method to output success responses.
*
* #param $data
* #return array
*/
private function successResponse($data)
{
// Success
return [
'IsError' => false,
'ErrorMsg' => '',
'Data' => $data
];
}
/**
* Method to get access token from rest server.
*
* #param $accountId
* #return string
* #throws \Exception
*/
private function getAccessToken($accountId)
{
// Define cache key
$cache_key = 'CA_REST_ACCESS_TOKEN.'. $accountId;
// Check if there is a cached version of access token
if (\Cache::has($cache_key))
return \Cache::get($cache_key);
// Anticipate errors
try
{
// Call rest api server
$response = self::curlPOST('/oauth2/token', [
'client_id' => $this->config['api_app_id'],
'grant_type' => 'soap',
'scope' => 'inventory',
'developer_key' => $this->config['api_developer_key'],
'password' => $this->config['api_password'],
'account_id' => $accountId
]);
// Check if there was an error
if (isset($response->Message))
throw new \Exception($response->Message);
if (isset($response->error))
throw new \Exception($response->error);
// Check if there was an invalid response
if (!isset($response->access_token) || !isset($response->expires_in))
throw new \Exception('Invalid response - '. json_encode($response));
// Cache server response
\Cache::add($cache_key, $response->access_token, floor($response->expires_in / 60));
// Success
return $response->access_token;
}
catch (\Exception $ex)
{
// Rethrow error
throw new \Exception('Failed to load rest api access token - '. $ex->getMessage());
}
}
/**
* Method to generate a HTTP POST request
*
* #param $endpoint
* #param array $fields
* #return string
* #throws \Exception
*/
private function curlPOST($endpoint, $fields = array())
{
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_USERPWD, $this->config['api_app_id'] .':'. $this->config['api_shared_secret']);
curl_setopt($ch, CURLOPT_URL, self::BASE_URL . $endpoint);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields, '', '&'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded'
));
curl_setopt($ch, CURLOPT_VERBOSE, true);
$verbose = fopen('php://temp', 'w+');
curl_setopt($ch, CURLOPT_STDERR, $verbose);
// Execute post request
$result = curl_exec($ch);
// Debug error
if ($result === FALSE) {
$curlError = 'Error #'. curl_errno($ch) .':'. htmlspecialchars(curl_error($ch));
rewind($verbose);
$verboseLog = stream_get_contents($verbose);
$curlError .= "\r\nDebug Info: ". htmlspecialchars($verboseLog);
curl_close($ch);
throw new \Exception($curlError);
}
#fclose($verbose);
// Close connection
curl_close($ch);
// Finished
return json_decode($result);
}
/**
* Method to generate HTTP GET request
*
* #param $accountId
* #param $queryString
* #return string
* #throws \Exception
*/
private function curlGET($accountId, $queryString)
{
// Open connection
$ch = curl_init();
// Set the url, query string & access token
curl_setopt($ch, CURLOPT_URL, self::BASE_URL . $queryString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '. self::getAccessToken($accountId)
));
curl_setopt($ch, CURLOPT_VERBOSE, true);
$verbose = fopen('php://temp', 'w+');
curl_setopt($ch, CURLOPT_STDERR, $verbose);
// Execute post request
$result = curl_exec($ch);
// TESTING
var_dump($result); exit;
// TESTING
// Debug error
if ($result === FALSE) {
$curlError = 'Error #'. curl_errno($ch) .':'. htmlspecialchars(curl_error($ch));
rewind($verbose);
$verboseLog = stream_get_contents($verbose);
$curlError .= "\r\nDebug Info: ". htmlspecialchars($verboseLog);
curl_close($ch);
throw new \Exception($curlError);
}
#fclose($verbose);
// Close connection
curl_close($ch);
// Finished
return json_decode($result);
}
}
The above is a façade class, so I use it like this:
echo '<pre>';
print_r(ChannelAdvisorREST::getStockUpdates
(
'xxx-xxx-xxx', // accountId
'2016-01-18T11:50:03.000Z' // lastSync utc date & time
));
echo '</pre>';
Any idea why it works in Postman REST Client, but fails in my PHP? I thought I am doing the exact same steps. I tried urlencode the query string also; but that did not work either.
I have solved it (for now) like this and it's working correctly for me. Let me know if there's a better/proper way to do this.
/**
* Method to generate HTTP GET request
*
* #param $accountId
* #param $queryString
* #return string
* #throws \Exception
*/
private function curlGET($accountId, $queryString)
{
// Open connection
$ch = curl_init();
// Set the url, query string & access token
curl_setopt($ch, CURLOPT_URL, self::BASE_URL . self::formatUri($queryString));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '. self::getAccessToken($accountId)
));
curl_setopt($ch, CURLOPT_VERBOSE, true);
$verbose = fopen('php://temp', 'w+');
curl_setopt($ch, CURLOPT_STDERR, $verbose);
// Execute post request
$result = curl_exec($ch);
// Debug error
if ($result === FALSE) {
$curlError = 'Error #'. curl_errno($ch) .':'. htmlspecialchars(curl_error($ch));
rewind($verbose);
$verboseLog = stream_get_contents($verbose);
$curlError .= "\r\nDebug Info: ". htmlspecialchars($verboseLog);
curl_close($ch);
throw new \Exception($curlError);
}
#fclose($verbose);
// Close connection
curl_close($ch);
// Finished
return json_decode($result);
}
/**
* Method to format query string
*
* #param $queryString
* #return string
*/
private function formatUri($queryString)
{
return str_replace(
['$', ' '],
['%24', '%20'],
$queryString
);
}

mobile.de search api Authorization fehler mit PHP curl

I tryed to get data from the "mobile.de Search API", but it doesn't work =/
.. this error cames every time :
HTTP Status 401 - This request requires HTTP authentication ().
.. what am I doing wrong?
$authCode = base64_encode("{Benutzername}:{Passwort}");
$uri = 'http://services.mobile.de/1.0.0/ad/search?modificationTime.min=2012-05-04T18:13:51.0Z';
$ch = curl_init($uri);
curl_setopt_array($ch, array(
CURLOPT_HTTPHEADER => array('Authorization: '.$authCode,'Accept-Language: de','Accept: application/xml'),
CURLOPT_RETURNTRANSFER =>true,
CURLOPT_VERBOSE => 1
));
$out = curl_exec($ch);
curl_close($ch);
echo $out;
As far as I can tell, I have complied with the interface description fully.
You need to set the following curl options for a correct authorization:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ); // HTTP Basic Auth
curl_setopt($curl, CURLOPT_USERPWD, $username.":".$password); // Auth String
A simplified version of my implementation:
<?
class APIProxy {
/* The access proxy for mobile.de search API */
private $username;
private $password;
private $api_base;
function __construct(){
/* Auth Data */
$this->username = '{username}';
$this->password = '{password}';
$this->api_base = 'http://services.mobile.de/1.0.0/';
}
function execute($query){
/* executes the query on remote API */
$curl = curl_init($this->api_base . $query);
$this->curl_set_options($curl);
$response = curl_exec($curl);
$curl_error = curl_error($curl);
curl_close($curl);
if($curl_error){ /* Error handling goes here */ }
return $response;
}
function get_auth_string(){
/* e.g. "myusername:mypassword" */
return $this->username.":".$this->password;
}
function curl_set_options($curl){
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ); // HTTP Basic Auth
curl_setopt($curl, CURLOPT_USERPWD, $this->get_auth_string()); // Auth String
curl_setopt($curl, CURLOPT_FAILONERROR, true); // Throw exception on error
curl_setopt($curl, CURLOPT_HEADER, false); // Do not retrieve header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Retrieve HTTP Body
}
}
$api = new APIProxy();
$result = $api->execute('ad/search?interiorColor=BLACK');
echo $result;
?>
A very basic non object oriented approach is using file get contents with manipulated header for accessing the search API. I share it to give a very simple example how the mobile.de API can be used. However, remember file_get_contents might be 30% - 50% slower than curl.
### Set language property in header (e.g. German) ###
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: de\r\n"
)
);
$baseURL = 'http://<<username>>:<<password>>#services.mobile.de/1.0.0/ad/search?';
$searchURL .= $searchString; ## provide get parameters e.g. color=red&make=bmw
##fetch your results
$file = file_get_contents($searchURL, false, $context);
Regarding the auth data. Mobile.de provides it for free for every dealer. Just generate the auth properties in your dealer dashboard.

PHP server side request to Microsoft Translator API throws ugly timeout error if slow connection

I have a server-side call with PHP to Bing translate to store input results from one language to English. If the connection is slow, the function will time out and throw an ugly PHP error that the time exceeded 30 seconds. Is there a way to stop the translation function attempt after 10 seconds and throw a custom error to the user that I've written an not throw a system error?
PHP code called in script:
//Translate product description from native language to english with Bing (Microsoft) API
if ($_POST['Translate_Code'] != 'en' ){//do not translate if already in english
require_once('./classes/Az1/BingTranslate.php');
$gt = new Az1_BingTranslateWrapper();
$lang_trans = $_POST['Translate_Code'];
/* Translate from "Native Language" to "English" */
$eng_description = $gt->translate($description, $lang_trans, "en");
} else{//language is english
$eng_description= $description;
}
Bing Translation Classes relevant:
class Az1_AccessTokenAuthentication {
/*
* Get the access token.
*
* #param string $grantType Grant type.
* #param string $scopeUrl Application Scope URL.
* #param string $clientID Application client ID.
* #param string $clientSecret Application client ID.
* #param string $authUrl Oauth Url.
*
* #return string.
*/
function getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl){
try {
//Initialize the Curl Session.
$ch = curl_init();
//Create the request Array.
$paramArr = array (
'grant_type' => $grantType,
'scope' => $scopeUrl,
'client_id' => $clientID,
'client_secret' => $clientSecret
);
//Create an Http Query.//
$paramArr = http_build_query($paramArr);
//Set the Curl URL.
curl_setopt($ch, CURLOPT_URL, $authUrl);
//Set HTTP POST Request.
curl_setopt($ch, CURLOPT_POST, TRUE);
//Set data to POST in HTTP "POST" Operation.
curl_setopt($ch, CURLOPT_POSTFIELDS, $paramArr);
//CURLOPT_RETURNTRANSFER- TRUE to return the transfer as a string of the return value of curl_exec().
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
//CURLOPT_SSL_VERIFYPEER- Set FALSE to stop cURL from verifying the peer's certificate.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//Execute the cURL session.
$strResponse = curl_exec($ch);
//Get the Error Code returned by Curl.
$curlErrno = curl_errno($ch);
if($curlErrno){
$curlError = curl_error($ch);
throw new Exception($curlError);
}
//Close the Curl Session.
curl_close($ch);
//Decode the returned JSON string.
$objResponse = json_decode($strResponse);
if ($objResponse->error){
throw new Exception($objResponse->error_description);
}
return $objResponse->access_token;
} catch (Exception $e) {
echo "Exception-".$e->getMessage();
}
}
}
/*
* Class:HTTPTranslator
*
* Processing the translator request.
*/
class Az1_HTTPTranslator {
/*
* Create and execute the HTTP CURL request.
*
* #param string $url HTTP Url.
* #param string $authHeader Authorization Header string.
* #param string $postData Data to post.
*
* #return string.
*
*/
function curlRequest($url, $authHeader, $postData=''){
//Initialize the Curl Session.
$ch = curl_init();
//Set the Curl url.
curl_setopt ($ch, CURLOPT_URL, $url);
//Set the HTTP HEADER Fields.
curl_setopt ($ch, CURLOPT_HTTPHEADER, array($authHeader,"Content-Type: text/xml"));
//CURLOPT_RETURNTRANSFER- TRUE to return the transfer as a string of the return value of curl_exec().
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
//CURLOPT_SSL_VERIFYPEER- Set FALSE to stop cURL from verifying the peer's certificate.
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, False);
if($postData) {
//Set HTTP POST Request.
curl_setopt($ch, CURLOPT_POST, TRUE);
//Set data to POST in HTTP "POST" Operation.
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
}
//Execute the cURL session.
$curlResponse = curl_exec($ch);
//Get the Error Code returned by Curl.
$curlErrno = curl_errno($ch);
if ($curlErrno) {
$curlError = curl_error($ch);
throw new Exception($curlError);
}
//Close a cURL session.
curl_close($ch);
return $curlResponse;
}
}
class Az1_BingTranslateWrapper{
protected $_clientID = "####"; //Client ID of the application
protected $_clientSecret = "####";//Client Secret key of the application
protected $_authUrl = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/";//OAuth Url
protected $_scopeUrl = "http://api.microsofttranslator.com";//Application Scope Url
protected $_grantType = "client_credentials";//Application grant type
protected $_accessToken = "";//Id generated from Microsoft
protected $_authHeader = "";//Takes access token created for input in Url
protected $_detectMethodUrl = "";//Forms Url for translation
protected $_strResponse = "";//translation of supplied text
public function translate($text, $lang_from, $lang_to){
//Create the AccessTokenAuthentication object.
$authObj = new Az1_AccessTokenAuthentication();
//Get the Access token.
$this->_accessToken = $authObj->getTokens($this->_grantType,$this->_scopeUrl,$this->_clientID,$this->_clientSecret,$this->_authUrl);
//Create the authorization Header string.
$this->_authHeader = "Authorization: Bearer ". $this->_accessToken;
//Create the Translator Object.
$translatorObj = new Az1_HTTPTranslator();
//HTTP Detect Method URL.
$this->_detectMethodUrl = "http://api.microsofttranslator.com/V2/Http.svc/Translate?text=".urlencode($text)."&from=".$lang_from."&to=".$lang_to;
//Ask for response as JSON
//Call the curlRequest.
$this->_strResponse = $translatorObj->curlRequest($this->_detectMethodUrl, $this->_authHeader);
//Remove XML formatting
$str_start = strrpos($this->_strResponse,'/">')+3;
$this->_strResponse = substr($this->_strResponse,$str_start,strlen($this->_strResponse)-$str_start-9);
return $this->_strResponse;
}
Ok youre using cURL - just set the CURLOPT_TIMEOUT as something less than your max_execution_time and then throw an exception on that timeout. and then handle that however... easy peasy :-)
It should be noted that values for CURLOPT_TIMEOUT are in seconds, but there is also CURLOPT_TIMEOUT_MS which is in milliseconds.
Additionally there are a number of additional options to deal with timeouts and speeds for connections, dns resolution, and overall bandwidth. You might also want to make use of those

file_get_contents prints text not sound

I'm trying to get a sound file to be printed on a php page. I'm using the code below. I thought when I run this script it would have shown a sound file to download but it prints some text. What do you think I should do to fix this?
<?php
$mylanguage=$_GET["mylanguage"];
$soundtext=$_GET["soundtext"];
echo stream_get_contents("http://api.microsofttranslator.com/V2/http.svc/Speak?appId=9CF5D9435A249BB484EC6DB50FFFB94C6733DEFB&language=$mylanguage&format=audio/wav&text=$soundtext");
?>
Send the correct headers. By default, PHP sends Content-Type: text/html. If you send something else, you have to send the headers by yourself.
What kind of sound file is this?
From PHP.net:
stream_get_contents
(PHP 5)
stream_get_contents — Reads remainder of a stream into a string
So it just returns a string representation of the file content. Not the file itself.
stream_get_contents does not work that way. It requires existing opened handled.
What you need is this,
$url = "http://api.microsofttranslator.com/V2/http.svc/Speak?appId=9CF5D9435A249BB484EC6DB50FFFB94C6733DEFB&language=$mylanguage&format=audio/wav&text=$soundtext";
$fh = fopen($url, "rb"); // this rb makes it binary safe
$audio_data = stream_get_contents($fh)
To echo it to client you need appropriate Content-Type header. Check /etc/mime.types to grab your proper content type.
Suppose its a wave audio. use the following code.
header("Content-type: audio/x-wav");
echo $audio_data;
This is the example on the ms api site: http://msdn.microsoft.com/en-us/library/ff512420.aspx#phpexample
Within the last try block you can see the header set header('Content-Type: audio/mp3');
<?php
class AccessTokenAuthentication {
/*
* Get the access token.
*
* #param string $grantType Grant type.
* #param string $scopeUrl Application Scope URL.
* #param string $clientID Application client ID.
* #param string $clientSecret Application client ID.
* #param string $authUrl Oauth Url.
*
* #return string.
*/
function getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl){
try {
//Initialize the Curl Session.
$ch = curl_init();
//Create the request Array.
$paramArr = array (
'grant_type' => $grantType,
'scope' => $scopeUrl,
'client_id' => $clientID,
'client_secret' => $clientSecret
);
//Create an Http Query.//
$paramArr = http_build_query($paramArr);
//Set the Curl URL.
curl_setopt($ch, CURLOPT_URL, $authUrl);
//Set HTTP POST Request.
curl_setopt($ch, CURLOPT_POST, TRUE);
//Set data to POST in HTTP "POST" Operation.
curl_setopt($ch, CURLOPT_POSTFIELDS, $paramArr);
//CURLOPT_RETURNTRANSFER- TRUE to return the transfer as a string of the return value of curl_exec().
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
//CURLOPT_SSL_VERIFYPEER- Set FALSE to stop cURL from verifying the peer's certificate.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//Execute the cURL session.
$strResponse = curl_exec($ch);
//Get the Error Code returned by Curl.
$curlErrno = curl_errno($ch);
if($curlErrno){
$curlError = curl_error($ch);
throw new Exception($curlError);
}
//Close the Curl Session.
curl_close($ch);
//Decode the returned JSON string.
$objResponse = json_decode($strResponse);
if ($objResponse->error){
throw new Exception($objResponse->error_description);
}
return $objResponse->access_token;
} catch (Exception $e) {
echo "Exception-".$e->getMessage();
}
}
}
Class HTTPTranslator {
/*
* Create and execute the HTTP CURL request.
*
* #param string $url HTTP Url.
* #param string $authHeader Authorization Header string.
*
* #return string.
*
*/
function curlRequest($url, $authHeader){
//Initialize the Curl Session.
$ch = curl_init();
//Set the Curl url.
curl_setopt ($ch, CURLOPT_URL, $url);
//Set the HTTP HEADER Fields.
curl_setopt ($ch, CURLOPT_HTTPHEADER, array($authHeader));
//CURLOPT_RETURNTRANSFER- TRUE to return the transfer as a string of the return value of curl_exec().
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
//CURLOPT_SSL_VERIFYPEER- Set FALSE to stop cURL from verifying the peer's certificate.
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, False);
//Execute the cURL session.
$curlResponse = curl_exec($ch);
//Get the Error Code returned by Curl.
$curlErrno = curl_errno($ch);
if ($curlErrno) {
$curlError = curl_error($ch);
throw new Exception($curlError);
}
//Close a cURL session.
curl_close($ch);
return $curlResponse;
}
}
try {
//Client ID of the application.
$clientID = "clientid";
//Client Secret key of the application.
$clientSecret = "clientsecret";
//OAuth Url.
$authUrl = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/";
//Application Scope Url
$scopeUrl = "http://api.microsofttranslator.com";
//Application grant type
$grantType = "client_credentials";
//Create the AccessTokenAuthentication object.
$authObj = new AccessTokenAuthentication();
//Get the Access token.
$accessToken = $authObj->getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl);
//Create the authorization Header string.
$authHeader = "Authorization: Bearer ". $accessToken;
//Set the params.
$inputStr = "Welcome";
$language = 'en';
$params = "text=$inputStr&language=$language&format=audio/mp3";
//HTTP Speak method URL.
$url = "http://api.microsofttranslator.com/V2/Http.svc/Speak?$params";
//Set the Header Content Type.
header('Content-Type: audio/mp3');
//Create the Translator Object.
$translatorObj = new HTTPTranslator();
//Call the curlRequest.
$strResponse = $translatorObj->curlRequest($url, $authHeader);
echo $strResponse;
} catch (Exception $e) {
echo "Exception: " . $e->getMessage() . PHP_EOL;
}
?>

Categories