-1
PHP函數用於獲取指定網址的標題,正文和http代碼? Curl庫沒有解析和操作http頭文件的最佳機制,所以這個函數非常方便。對於需要這種功能的小型腳本來說,使用一些大而健壯的庫已經令人厭煩。爲給定url獲取標題,正文和http代碼的函數?
PHP函數用於獲取指定網址的標題,正文和http代碼? Curl庫沒有解析和操作http頭文件的最佳機制,所以這個函數非常方便。對於需要這種功能的小型腳本來說,使用一些大而健壯的庫已經令人厭煩。爲給定url獲取標題,正文和http代碼的函數?
這裏是我的,捲曲這樣的功能:
<?php
function get_url_data($url, $timeout = 5){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 2);
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');
$response = curl_exec($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);
$headers = explode("\n", $header);
$code = 0;
if(isset($headers[0])){
if(preg_match('/[0-9]{3}/', $headers[0], $matches)){
$code = $matches[0];
}
}
return ['code' => $code, 'headers' => $headers, 'body' => $body];
}
echo '<pre>';
$timeout = 5;
$url = "http://www.ebay.com";
$results = get_url_data($url, $timeout);
print_r($results);
echo '</pre>';
實例進行測試,做工精細,享受。
omg,你可以使用curl的$ http_response_header。 – fico7489