報Warning: file_get_contents(http://www.dianping.com/shop/8042874) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden inF:\work\www.xxxx.com\phpQuery.php on line 4767 錯誤,
因為file_get_contents未進行模擬瀏覽器被服務器拒絕訪問
解決方法
function get_fcontent($url, $timeout = 5 ) { $url = str_replace( "&", "&", urldecode(trim($url)) ); $cookie = tempnam ("/tmp", "CURLCOOKIE"); $ch = curl_init();
//模擬瀏覽器 在HTTP請求中包含一個"User-Agent: "頭的字符串。 curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
//需要獲取的URL地址,也可以在 curl_init()函數中設置。 curl_setopt( $ch, CURLOPT_URL, $url);
//連接結束后保存cookie信息的文件。 curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie );
//啟用時會將服務器服務器返回的"Location: "放在header中遞歸的返回給服務器,使用CURLOPT_MAXREDIRS可以限定遞歸返回的數量。 curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
//HTTP請求頭中"Accept-Encoding: "的值。支持的編碼有"identity","deflate"和"gzip"。如果為空字符串"",請求頭會發送所有支持的編碼類型。
在cURL 7.10中被加入。 curl_setopt( $ch, CURLOPT_ENCODING, "" );
//將 curl_exec()獲取的信息以文件流的形式返回,而不是直接輸出。 curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
//當根據Location:重定向時,自動設置header中的Referer:信息。 curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
//禁用后cURL將終止從服務端進行驗證。使用CURLOPT_CAINFO選項設置證書使用CURLOPT_CAPATH選項設置證書目錄 如果CURLOPT_SSL_VERIFYPEER(默認值為2)被啟用,CURLOPT_SSL_VERIFYHOST需要被設置成TRUE否則設置為FALSE。
自cURL 7.10開始默認為TRUE。從cURL 7.10開始默認綁定安裝。 curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false ); # required for https urls
//在發起連接前等待的時間,如果設置為0,則無限等待。 curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
//設置cURL允許執行的最長毫秒數。 curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
//指定最多的HTTP重定向的數量,這個選項是和CURLOPT_FOLLOWLOCATION一起使用的。 curl_setopt( $ch, CURLOPT_MAXREDIRS, 10 ); $content = curl_exec( $ch ); curl_close ( $ch ); return $content; }
//詳細每個curlopt意思.轉http://www.jb51.net/article/39331.htm
$url = 'http://www.dianping.com/shop/8042874'; $content = get_fcontent($url); phpQuery::newDocumentHTML($content); $main = pq('.shop-name')->html(); echo $main;