background image

php curl 分离 header 和 body 信息

本文章来给大家详细介绍关于在

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_rdq
IYkjFDMollzI_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.goole.com/support/accounts/bin/answer.py?
h1=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>