2013-03-26 69 views
0

這是$result回報:如何從原始HTTP響應中檢索特定的頭字段?

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 protected]</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次。

+1

爲它寫一個方法?使用像XML這樣的自描述結構? – Patashu 2013-03-26 00:26:32

+0

你建議這樣的「方法」是什麼? – 2013-03-26 00:27:04

+0

您可以給出一個您在$ result中獲得的數據的示例,以及您在$ INFO_I_NEED中需要的部分? – Kara 2013-03-26 00:28:21

回答

1

看起來preg_match_all可能是你在找什麼。使用this answer作爲靈感嘗試:

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', 
) 
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]); 

} 
?>