卷曲返回标题 - 如何获取值标题?

时间:2016-08-01 01:26:42

标签: php curl http-headers

$ch = curl_init();
$url = "https://ttr.test.ru/";
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER, 1);
$result = curl_exec($ch);  
curl_close($ch);

curl返回下一个文字(标题):

HTTP/1.1 202 Test
Access-Control-Headers: X-PHP-TEST-1, X-PHP-TEST-2, X-PHP-TEST-3
Content-Type: text/plain; charset=utf-8
X-PHP-TEST-1: a43edefa03d32ee8a5183a0662bb82e6
X-PHP-TEST-2: 85628
X-PHP-TEST-3: 2434234234
Date: Mon, 01 Aug 2016 01:03:25 GMT

如何获取值HTTP/1.1(202),X-PHP-TEST-1X-PHP-TEST-2X-PHP-TEST-3

2 个答案:

答案 0 :(得分:0)

您可以拆分结果:

$ch = curl_init();
$url = "https://ttr.test.ru/";
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);  
curl_close($ch);

$ret_headers = explode("\n", explode("\r\n\r\n", $result)[0]);
$headers = [];


array_shift($ret_headers);

foreach ($ret_headers as $header_str) {
    $h = explode(":", $header_str);
    $headers[trim($h[0])] = trim($h[1]);
}

print_r($headers);

答案 1 :(得分:0)

等待回复时写了自己的版本:

$ch = curl_init();
$url = "https://auth.selcdn.ru/";
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Auth-User:".UPLOAD_FILES__IMG2_MENU_CAFE__LOGIN, "X-Auth-Key:".UPLOAD_FILES__IMG2_MENU_CAFE__PASSWORD));

$result = curl_exec($ch);  
curl_close($ch);
$arr1 = split("\r\n", $result);
$arr2 = array();
foreach($arr1 as $key=>$val){
    if($key === 0){ //for get code HTTP
        $el = explode(' ',$val);
        $arr2[$el[0]] = $el[1];
    }
    elseif($val != ''){
        $el = explode(': ',$val);
        $arr2[$el[0]] = $el[1];
    }
}