1

我有一个使用 PHP 到 Bing 的服务器端调用,将输入结果从一种语言存储为英语。如果连接速度很慢,该函数将超时并抛出一个时间超过 30 秒的丑陋 PHP 错误。有没有办法在 10 秒后停止翻译功能尝试并向用户抛出我写的自定义错误,而不是抛出系统错误?

脚本中调用的 PHP 代码:

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

必应翻译类相关:

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

1 回答 1

2

好的,您正在使用 cURL - 只需将其设置CURLOPT_TIMEOUT为小于您的 max_execution_time 的值,然后在该超时时抛出异常。然后处理它......简单的peasy :-)

应该注意的是,值以CURLOPT_TIMEOUT秒为单位,但也有CURLOPT_TIMEOUT_MS以毫秒为单位的值。

此外,还有许多其他选项可以处理超时和连接速度、dns 分辨率和整体带宽。您可能还想利用这些

于 2012-11-26T23:29:19.913 回答