我可以多次拨打curl_setopt
CURLOPT_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);
答案 0 :(得分:95)
请求内部针对请求执行curl(通过this answer to "Php - Debugging Curl"中列出的方法)回答问题:否,无法使用curl_setopt
调用CURLOPT_HTTPHEADER
。第二个呼叫将覆盖第一个呼叫的标头。
相反,需要使用所有标题调用该函数一次:
$headers = array(
'Content-type: application/xml',
'Authorization: gfhjui',
);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);
相关(但不同)的问题是:
答案 1 :(得分:10)
其他类型的格式:
$headers[] = 'Accept: application/json';
$headers[] = 'Content-Type: application/json';
$headers[] = 'Content-length: 0';
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);
答案 2 :(得分: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'
* ];
*/
$i_header = $header;
if(is_array($i_header) === true){
$header = [];
foreach ($i_header as $param => $value) {
$header[] = "$param: $value";
}
}