我如何使POST使用X-HTTP-Method-Override与PHP curl请求


How do I make a POST using X-HTTP-Method-Override with a PHP curl request?

我正在使用谷歌翻译API,并且有可能我可以发送相当多的文本进行翻译。在此场景中,Google建议执行以下操作:

如果你想发送更多的数据,你也可以使用POST来调用API在单个请求中。POST主体中的q参数必须较小超过5K个字符。要使用POST,必须使用X-HTTP-Method-Override头告诉Translate API处理请求作为GET(使用X-HTTP-Method-Override: GET)。谷歌翻译API文档

我知道如何用CURL发出一个正常的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-Method-Override?

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

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'));

使用CURLOPT_HTTPHEADER选项从字符串数组中添加标题

对我来说还不够,我需要使用http_build_query来处理我的数组post数据我的完整示例:

  $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/希望对大家有所帮助