2

我一直在使用 PHP curl 从远程网站获取我需要的数据。这是我使用的 cURL 函数:

function get_content($adr)  
    {  
       $ch = curl_init();  

       curl_setopt ($ch, CURLOPT_URL, $adr);  
       curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
       curl_setopt ($ch, CURLOPT_HEADER, 0);  

       ob_start();  

       curl_exec ($ch);  
       curl_close ($ch);  
       $string = ob_get_contents();  

       ob_end_clean();  

       return $string;      

    }  
$myrul = "http://remoteurl.com";
$result = get_content($myrul);

但是如何获取响应的标头?

4

1 回答 1

3

如果我上面的评论是正确的,请更改:

curl_setopt($ch, CURLOPT_HEADER, 0);

到:

curl_setopt($ch, CURLOPT_HEADER, 1);

并根据您认为合适的方式解析返回的标头。请注意,仅在函数中更改上述内容将返回标头内容,因此如果您只想返回标头:

function http_head_curl($url,$timeout=10)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); // in seconds
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $res = curl_exec($ch);
    if ($res === false) {
        throw new RuntimeException("cURL exception: ".curl_errno($ch).": ".curl_error($ch));
    }
    return trim($res);
}
于 2012-12-13T14:25:30.743 回答