0

这是$result返回的内容:

HTTP/1.1 200 OK
Server: SERVER
Content-Type: text/xml;charset=utf-8
Connection: close
Expires: Tue, 26 Mar 2013 00:28:45 GMT
Cache-Control: max-age=0, no-cache, no-store
Pragma: no-cache
Date: Tue, 26 Mar 2013 00:28:45 GMT
Content-Length: 290
Connection: keep-alive
Set-Cookie: KEY=isbgvigbiwsb124252525252; Domain=www.website.com; Expires=Tue, 26-Mar-13 02:28:44 GMT; Path=/; HttpOnly
Set-Cookie: session=12345566789:abc1231552662626262; Domain=www.website.com; Expires=Thu, 25-Apr-2013 00:28:43 GMT; Path=/


<login>
  <success>1</success>
  <player>
     <id>1234567</id>
     <AnotherId>123456</AnotherId>
     <email>email@email.com</email>
      <accountinformation>
          <id>123456</id>
          <name>namehere</name>
          <number>1234360</number>
       </accountinformation>  
   </player>
</login>

我想KEY从响应中检索 cookie。目前我的代码如下

//a cURL function would be here
$result = curl_exec($ch); 

list($body, $split) = explode("\r\n\r\n", $result, 2);
$arr = explode("\r\n", $body);   

$start = explode(":", $arr[10]);    
$end = explode(";", $start[1]);
$INFO_I_NEED = $end[0];    

执行此操作的更简单方法是什么?因为它需要针对不同的解析区域进行 3/4 次。

4

2 回答 2

1

看起来preg_match_all可能是您正在寻找的东西。使用这个答案作为灵感尝试:

preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $m);

然后你可以写一个这样的函数:

function getCookies($result) {
    preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $m);
    return($m)
}

$result = curl_exec($ch);
$cookiesArray = getCookies($result);

该函数的返回值将是一个包含所有 cookie 值的数组。所以$cookiesArray会举行:

array (
  0 => 'KEY=isbgvigbiwsb124252525252',
  1 => 'session=12345566789:abc1231552662626262',
)
于 2013-03-26T01:12:39.877 回答
0

将它放在一个函数中,以便您可以在需要时重用:

<?php
//a cURL function would be here
$result = curl_exec($ch); 

$INFO_I_NEED = myExplode($result);

function myExplode($data){

    list($body, $split) = explode("\r\n\r\n", $result, 2);
    $arr = explode("\r\n", $body);   

    $start = explode(":", $arr[10]);    
    $end = explode(";", $start[1]);

    return($end[0]);

}
?>
于 2013-03-26T00:30:58.203 回答