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

时间:2014-06-01 20:18:56

标签: 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);
        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并将其分配给变量? Thankss,

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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);

?>