phpcurl分離header和body資訊

suboysugar發表於2015-04-28

php中可以通過curl來模擬http請求,同時可以獲取http response header和body,當然也設定引數可以只獲取其中的某一個。當設定同時獲取response header和body時候,它們會一同作為結果返回。這時需要我們自己來分離它們。

下面程式碼是模擬向google一個http GET請求

function httpGet() {
    $url = `http://www.google.com.hk`;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, TRUE);    //表示需要response header
    curl_setopt($ch, CURLOPT_NOBODY, FALSE); //表示需要response body
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
    curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
    curl_setopt($ch, CURLOPT_TIMEOUT, 120);
    $result = curl_exec($ch);
    if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == `200`) {
        return $result;
    }
    return NULL;
}

呼叫上述方法後看到如下類似輸出:

HTTP/1.1 200 OK
Date: Tue, 09 Jul 2013 14:21:08 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=UTF-8
Set-Cookie: PREF=ID=75e996a7ad21f47b:FF=0:NW=1:TM=1373379668:LM=1373379668:S=TTLQQN-jwGDYnkkY; expires=Thu, 09-Jul-2015 14:21:08 GMT; path=/; domain=.google.com.hk
Set-Cookie: NID=67=PPu7FfFeuZqwfsrUifgzjidX4JZxxCPLe9xFHjdXhfHpzs3gaykFSH5uGXy2esWTlp_rdqIYkjFDMollzI_sA-8owxD3mDh6KCRwdMa9-g5VChj0E5XAGNjo9d-sZfLN; expires=Wed, 08-Jan-2014 14:21:08 GMT; path=/; domain=.google.com.hk; HttpOnly
P3P: CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."
Server: gws
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Transfer-Encoding: chunked
<!doctype html>Google(function(){
window.google={kEI:"VBzcUdWuHOmtiQf64IHoCw",getEI:function(a){for(var b;a&&(!a.getAttribute||!(b=a.getAttribute("eid")));
……

這裡可以看到結果中header和body資訊是在一起的,那麼如何分離它們呢。方法有二種,一是通過curl自帶的curl_getinfo()方法獲取頭的長度,然後使用substr來分割字串。示例程式碼如下:

$response = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == `200`) {
    $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $header = substr($response, 0, $headerSize);
    $body = substr($response, $headerSize);
}

第二種方法基於header和body是通過兩個回車換行來分割的,所以可以通過如下程式碼實現:

$response = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == `200`) {
    list($header, $body) = explode("

", response, 2);
}

如何聯絡我:【萬里虎】www.bravetiger.cn
【QQ】3396726884 (諮詢問題100元起,幫助解決問題500元起)
【部落格】http://www.cnblogs.com/kenshinobiy/


相關文章