本文章來給大家詳細介紹關於在php curl 分離header和body信息測試實例,以前可能大家沒注意,後來分析了一下,下面給大家介紹。
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><html itemscope="itemscope" itemtype="http://schema.org/WebPage"><head><meta itemprop="image" content="/images/google_favicon_128.png"><title>Google</title><script>(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("rnrn", response, 2);
}