$my_curl = curl_init(); //初始化一個curl對象 curl_setopt($my_curl, CURLOPT_URL, "http://www.webjoy.net"); //設置你需要抓取的URL curl_setopt($my_curl,CURLOPT_RETURNTRANSFER,1); //設置是將結果保存到字符串中還是輸出到屏幕上,1表示將結果保存到字符串 $str = curl_exec($curl); //執行請求 echo $str; //輸出抓取的結果 curl_close($curl); //關閉url請求 // 封裝 function curl_file_get_contents($url){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_TIMEOUT, 5); curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_); curl_setopt($ch, CURLOPT_REFERER,_REFERER_); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $r = curl_exec($ch); curl_close($ch); return $r; }
<?php
function HTTP_Post($URL,$data,$cookie, $referrer="")
{
// parsing the given URL
$URL_Info=parse_url($URL);
// Building referrer
if($referrer=="") // if not given use this script as referrer
$referrer="111″;
// making string from $data
foreach($data as $key=>$value)
$values[]="$key=".urlencode($value);
$data_string=implode("&",$values);
// Find out which port is needed – if not given use standard (=80)
if(!isset($URL_Info["port"]))
$URL_Info["port"]=80;
// building POST-request:
$request.="POST ".$URL_Info["path"]." HTTP/1.1n";
$request.="Host: ".$URL_Info["host"]."n";
$request.="Referer: $referern";
$request.="Content-type: application/x-www-form-urlencodedn";
$request.="Content-length: ".strlen($data_string)."n";
$request.="Connection: closen";
$request.="Cookie: $cookien";
$request.="n";
$request.=$data_string."n";
$fp = fsockopen($URL_Info["host"],$URL_Info["port"]);
fputs($fp, $request);
while(!feof($fp)) {
$result .= fgets($fp, 1024);
}
fclose($fp);
return $result;
}
?>
php中 curl, fsockopen ,file_get_contents 三個函數 都可以實現采集模擬發言 。三者有什么區別,或者講究么
趙永斌:
有些時候用file_get_contents()調用外部文件,容易超時報錯。換成curl后就可以.具體原因不清楚
curl 效率比file_get_contents()和fsockopen()高一些,原因是CURL會自動對DNS信息進行緩存(亮點啊有我待親測)
范佳鵬:
file_get_contents curl fsockopen
在當前所請求環境下選擇性操作,沒有一概而論:
具我們公司開發KBI應用來看:
剛開始采用:file_get_contents
后來采用:fsockopen
最后到至今采用:curl
(遠程)我個人理解到的表述如下(不對請指出,不到位請補充)
file_get_contents 需要php.ini里開啟allow_url_fopen,請求http時,使用的是http_fopen_wrapper,不會keeplive.curl是可以的。
file_get_contents()單個執行效率高,返回沒有頭的信息。
這個是讀取一般文件的時候並沒有什么問題,但是在讀取遠程問題的時候就會出現問題。
如果是要打一個持續連接,多次請求多個頁面。那么file_get_contents和fopen就會出問題。
取得的內容也可能會不對。所以做一些類似采集工作的時候,肯定就有問題了。
sock較底層,配置麻煩,不易操作。 返回完整信息。
潘少寧-騰訊:
file_get_contents 雖然可以獲得某URL的內容,但不能post get啊。
curl 則可以post和get啊。還可以獲得head信息
而socket則更底層。可以設置基於UDP或是TCP協議去交互
file_get_contents 和 curl 能干的,socket都能干。
socket能干的,curl 就不一定能干了
file_get_contents 更多的時候 只是去拉取數據。效率比較高 也比較簡單。
趙的情況這個我也遇到過,我通過CURL設置host 就OK了。 這和網絡環境有關系
