当前位置:Gxlcms > PHP教程 > 把curl回来的cookies处理成数组

把curl回来的cookies处理成数组

时间:2021-07-01 10:21:17 帮助过:24人阅读

把curl返回的cookies处理成数组
目的只是将Curl返回的Header里面的Cookies转化成数组和获取Location

例子:
……
Cache-Control: private,no-cache="set-cookie"
Expires: -1
Pragma: no-cache
Location: http://example.com/
Set-Cookie: B=1; Path=/
Set-Cookie: C=5; Path=/
Set-Cookie: R=5; Path=/
转成
array("B" => "1","C" => "5","R" => "5" )
并取出 Location 为 $l="http://example.com/";

谢谢了
------解决方案--------------------
$s = <<< TXT
Cache-Control: private,no-cache="set-cookie"
Expires: -1
Pragma: no-cache
Location: http://example.com/
Set-Cookie: B=1; Path=/
Set-Cookie: C=5; Path=/
Set-Cookie: R=5; Path=/
TXT;

$res = array();
foreach(preg_split("/[\r\n]+/", $s, -1, PREG_SPLIT_NO_EMPTY) as $row) {
switch($k = strtok($row, ':')) {
case 'Location':
$res[$k][] = trim(strtok(''));
break;
case 'Set-Cookie':
$res[$k][trim(strtok('='))] = trim(strtok(';'));
break;
}
}
print_r($res);
Array
(
[Location] => Array
(
[0] => http://example.com/
)

[Set-Cookie] => Array
(
[B] => 1
[C] => 5
[R] => 5
)

)

人气教程排行