2011-10-20 28 views
5

我正在使用Google Translate API,並且可能會發送相當多的要翻譯的文本。在此之情況谷歌建議做到以下幾點:如何使用帶有PHP curl請求的X-HTTP-Method-Override進行POST?

您還可以使用POST來調用API,如果你想在一個單一的請求發送更多數據 。 POST主體中的q參數必須小於5K個字符的 。要使用POST,必須使用 X-HTTP-Method-Override標頭告訴Translate API將 請求視爲GET(使用X-HTTP-Method-Override:GET)。 Google Translate API Documentation

我知道該怎麼做,捲曲正常的POST請求:

$curl = curl_init(); 
curl_setopt($curl, CURLOPT_URL, $url); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($curl, CURLOPT_POST, 1); 
curl_setopt($curl, CURLOPT_POSTFIELDS, $data); 
$response = curl_exec($curl); 
curl_close($curl); 
echo $response; 

但是我怎麼修改標題中使用X-HTTP-方法,改寫?

回答

6
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: GET')); 
+0

完善!這正是我需要的。 – ashansky

+0

這個工作適合你嗎?我仍然得到壞請求。 ( – tofutim

0

使用CURLOPT_HTTPHEADER選項從一個字符串數組

1

http://php.net/manual/en/function.curl-setopt.php

CURLOPT_HTTPHEADER

HTTP報頭字段的陣列設置添加的報頭,在格式array('Content-type: text/plain', 'Content-length: 100')

因此,

curl_setopt($curl, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: GET')); 
0

沒有足夠的對我來說,我需要使用http_build_query FO我的數組後的數據 我的完整的例子:

$param = array(
    'key' => 'YOUR_API_KEY_HERE', 
    'target' => 'en', 
    'source' => 'fr', 
    "q" => 'text to translate' 
    ); 
    $formData = http_build_query($param); 
    $headers = array("X-HTTP-Method-Override: GET"); 
    $ch=curl_init(); 

    curl_setopt($ch, CURLOPT_POST, 1); 

    curl_setopt($ch, CURLOPT_POSTFIELDS,$formData); 
    curl_setopt($ch, CURLOPT_HTTPHEADER,$headers); 
    curl_setopt($ch, CURLOPT_REFERER, 'http://yoursite'); //if you have refere domain restriction for your google API KEY 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_URL,'https://www.googleapis.com/language/translate/v2'); 
    $query = curl_exec($ch); 
    $info = curl_getInfo($ch); 
    $error = curl_error($ch); 
    $data = json_decode($query,true); 

    if (!is_array($data) || !array_key_exists('data', $data)) { 
    throw new Exception('Unable to find data key'); 
    } 
    if (!array_key_exists('translations', $data['data'])) { 
    throw new Exception('Unable to find translations key'); 
    } 
    if (!is_array($data['data']['translations'])) { 
    throw new Exception('Expected array for translations'); 
    } 
    foreach ($data['data']['translations'] as $translation) { 
    echo $translation['translatedText']; 
    } 

我在這裏找到這個幫助https://phpfreelancedeveloper.wordpress.com/2012/06/11/translating-text-using-the-google-translate-api-and-php-json-and-curl/ 希望幫助