83

我可以多次调用curl_setoptCURLOPT_HTTPHEADER设置多个标题吗?

$url = 'http://www.example.com/';

$curlHandle = curl_init($url);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array('Content-type: application/xml'));
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array('Authorization: gfhjui'));

$execResult = curl_exec($curlHandle);
4

3 回答 3

132

按照 curl 在内部对请求所做的操作(通过“Php - Debugging Curl”的答案中概述的方法)回答了这个问题:

不,不能多次使用curl_setopt调用,CURLOPT_HTTPHEADER每次都传递一个标头,以便设置多个标头。

第二次调用将覆盖前一次调用(例如第一次调用)的标题。

相反,该函数需要使用所有标头调用一次:

$headers = array(
    'Content-type: application/xml',
    'Authorization: gfhjui',
);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);

相关(但不同)的问题是:

于 2013-02-28T11:38:25.120 回答
14

其他类型的格式:

$headers[] = 'Accept: application/json';
$headers[] = 'Content-Type: application/json';
$headers[] = 'Content-length: 0';

curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);
于 2016-11-15T15:18:46.690 回答
0
/**
 * If $header is an array of headers
 * It will format and return the correct $header
 * $header = [
 *  'Accept' => 'application/json',
 *  'Content-Type' => 'application/x-www-form-urlencoded'
 * ];
 */
$header; //**
if (is_array($header)) {
    $i_header = $header;
    $header = [];
    foreach ($i_header as $param => $value) {
        $header[] = "$param: $value";
    }
}
于 2020-06-11T15:36:46.343 回答