1

我有一段代码试图调用 Cloudstack REST API:

function file_get_header($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 1);

        $datas = curl_exec($ch);
        curl_close($ch);
        return $datas;
} 

        $url = "http://10.151.32.51:8080/client/api?" . $command . "&" . $signature . "&" . $response;

        echo $test = file_get_header($url);

输出是这样的:

HTTP/1.1 200 OK 服务器:Apache-Coyote/1.1 Set-Cookie:JSESSIONID=74A5104C625549EB4F1E8690C9FC8FC1;Path=/client Content-Type: text/javascript;charset=UTF-8 Content-Length: 323 Date: Sun, 01 Jun 2014 20:08:36 GMT

我要做的是如何仅打印 JSESSIONID=74A5104C625549EB4F1E8690C9FC8FC1 并将其分配给变量?谢谢,

4

2 回答 2

2

这是一种将所有标头解析为一个不错的关联数组的方法,因此您可以通过请求获得任何标头值$dictionary['header-name']

$url = 'http://www.google.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$datas = curl_exec($ch);

$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($datas, 0, $header_size);
curl_close($ch);

echo ($header);
$arr = explode("\r\n", $header);
$dictionary = array();
foreach ($arr as $a) {
    echo "$a\n\n";
    $key_value = explode(":", $a, 2);
    if (count($key_value) == 2) {
        list($key, $value) = $key_value;
        $dictionary[$key] = $value;
    }
}

//uncomment the following line to see $dictionary is an associative-array of Header keys to Header values
//var_dump($dictionary);
于 2014-06-01T20:32:23.150 回答
0

很简单,只需匹配您想要的字符串部分preg_match

<?php

    $text = "HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Set-Cookie: JSESSIONID=74A5104C625549EB4F1E8690C9FC8FC1; Path=/client    Content-Type: text/javascript;charset=UTF-8 Content-Length: 323 Date: Sun, 01 Jun 2014 20:08:36 GMT";

    preg_match("/JSESSIONID=\\w{32}/u", $text, $match);

    echo $result = implode($match);

?>
于 2014-06-01T20:43:12.233 回答