PHP CURL从URL获取标头并将其设置为变量

PHP CURL从URL获取标头并将其设置为变量,php,api,rest,curl,apache-cloudstack,Php,Api,Rest,Curl,Apache Cloudstack,我有一段代码试图调用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); re

我有一段代码试图调用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内容类型:text/javascript;字符集=UTF-8内容长度:323日期:2014年6月1日星期日20:08:36 GMT


我试图做的是如何仅打印JSESSIONID=74A5104C625549EB4F1E8690C9FC8FC1并将其分配到变量中?谢谢,

这里有一个方法可以将所有的头解析成一个漂亮的关联数组,因此您可以通过请求
$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);

很简单,只需将所需字符串部分与
preg\u 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);

?>