国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > PHP > 正文

php curl 分離header和body信息

2024-05-04 21:47:29
字體:
來源:轉載
供稿:網友

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

下面代碼是模擬向google一個http GET請求,代碼如下:

  1. function httpGet() { 
  2.     $url = 'http://www.google.com.hk'
  3.     $ch = curl_init(); 
  4.     curl_setopt($ch, CURLOPT_URL, $url); 
  5.     curl_setopt($ch, CURLOPT_HEADER, TRUE);    //表示需要response header 
  6.     curl_setopt($ch, CURLOPT_NOBODY, FALSE); //表示需要response body 
  7.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
  8.     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE); 
  9.     curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE); 
  10.     curl_setopt($ch, CURLOPT_TIMEOUT, 120); 
  11.     $result = curl_exec($ch); 
  12.     if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == '200') { 
  13.         return $result
  14.     } 
  15.     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來分割字符串,示例代碼如下:

  1. $response = curl_exec($ch); 
  2. if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == '200') { 
  3.     $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE); 
  4.     $header = substr($response, 0, $headerSize); 
  5.     $body = substr($response$headerSize); 

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

  1. $response = curl_exec($ch); 
  2. if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == '200') { 
  3.     list($header$body) = explode("rnrn", response, 2); 
  4. }

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 治县。| 青浦区| 平江县| 周口市| 黑水县| 云浮市| 溧阳市| 南开区| 东莞市| 平定县| 黄石市| 屏东县| 沛县| 虞城县| 汉川市| 榆社县| 保亭| 日喀则市| 营山县| 上虞市| 固安县| 永平县| 桂林市| 左权县| 华宁县| 哈尔滨市| 神农架林区| 乌苏市| 眉山市| 苏尼特右旗| 沙坪坝区| 浦城县| 千阳县| 建平县| 高密市| 呼玛县| 安平县| 惠来县| 靖远县| 罗江县| 札达县|