php中能夠經過curl來模擬http請求,同時能夠獲取http response header和body,固然也設置參數能夠只獲取其中的某一個。當設置同時獲取response header和body時候,它們會一同做爲結果返回。這時須要咱們本身來分離它們。php
下面代碼是模擬向google一個http GET請求html
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; }
調用上述方法後看到以下相似輸出:dom
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來分割字符串。示例代碼以下:curl
$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是經過兩個回車換行來分割的,因此能夠經過以下代碼實現:google
$response = curl_exec($ch); if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == '200') { list($header, $body) = explode("\r\n\r\n", response, 2); }