2012年3月4日 星期日

PHP 抓網頁內容

1.file_get_contents

PHP代碼
$url = http://www.xxx.com/;
$contents = file_get_contents($url);
//如果出現中文亂碼使用下面代碼
//$getcontent = iconv("gb2312", "utf-8",file_get_contents($url)); 
//echo $getcontent;
echo $contents;
2.curl

PHP代碼
$url = "http://www.xxx.com/";
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
//在需要用戶檢測的網頁里需要增加下面兩行
//curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
//curl_setopt($ch, CURLOPT_USERPWD, US_NAME.":".US_PWD);
$contents = curl_exec($ch);
curl_close($ch);
echo $contents;


3.fopen->fread->fclose

PHP代碼
$handle = fopen ("http://www.xxx.com/", "rb");
$contents = "";
do {
   $data = fread($handle, 8192);
   if (strlen($data) == 0) {
   break;
   }
   $contents .= $data;
} while(true);
fclose ($handle);
echo $contents;