file_get_contents prints text not sound - php

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;
}
?>

Related

Get Multiple Translations using Microsoft Translator API

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.

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.

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

cURL POST Request to API in PHP not returning any values

I'm attempting to obtain an access token for Microsoft's Translator API, and it's been quite a struggle. I first tried to write the request with Ruby and HTTParty, but it wasn't accepting my parameters. Microsoft provided an example in PHP, so I figured I could just use that:
http://msdn.microsoft.com/en-us/library/hh454950.aspx#phpexample
The code was copied directly from the Microsoft website--I just added in my variables and called the function at the end:
<?php
/*
* 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);
}
$finalresponse = $objResponse->access_token;
return $finalresponse;
} catch (Exception $e) {
echo "Exception-".$e->getMessage();
}
}
$grant = "client_credentials"
$scope = "http://api.microsofttranslator.com";
$secret = "8Bo0SET1W8lmDgfV/l7FLEKUWRDXCEZrvTgv9tSH3Bs=";
$client = "globalchatapp"
$auth = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/";
getTokens($grant, $scope, $client, $secret, $auth);
?>
Anyway, when I run this (using PHP 5.3.6) there are no errors; it doesn't return any value. I'm not great with PHP, and it could be something glaringly obvious that I just haven't seen, but I've struggled with it for awhile to no avail. Any help would be greatly appreciated.
Also, if this helps, here was my original Ruby code. I did receive a response from the server here, saying 'scope' was missing:
require 'httparty'
scope = "http://api.microsofttranslator.com";
secret = "8Bo0SET1W8lmDgfV/l7FLEKUWRDXCEZrvTgv9tSH3Bs=";
auth = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/";
client_id = "globalchatapp"
grant_type = "client_credentials"
response = HTTParty.post("https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/?&scope=#{scope}&secret=#{secret}&client_id=#{client_id}&grant_type=#{grant_type}", :body => {:key => :value})
puts response
Thanks again!
Store the value returned by getTokens() in a variable and pass it to urldecode() to decode the %2F and other encoded characters.
$tokens = getTokens($grant, $scope, $client, $secret, $auth);
echo urldecode($tokens);

Categories