curl post,file_get_contents post,curl file_get_contents post請(qǐng)求數(shù)據(jù)
在PHP中cURL、file_get_contents函數(shù)均可以獲取遠(yuǎn)程鏈接的數(shù)據(jù),但是file_get_contents的可控制性不太好,對(duì)于各種復(fù)雜情況的數(shù)據(jù)采集情景,file_get_contents顯得有點(diǎn)無(wú)能為力,cURL在數(shù)據(jù)采集情景復(fù)雜的環(huán)境下略顯優(yōu)勢(shì)。cURL函數(shù)的curl_setopt里面還有很多參數(shù),讀者可以抽空整體看一遍,雖然平時(shí)未必用得上,但是至少做到心里有底,知道都有哪些參數(shù),必要時(shí)還能找出來(lái)使用。本文僅粗略介紹了file_get_contents函數(shù)和cURL函數(shù)的基本使用:
curl post方式獲取數(shù)據(jù),調(diào)用示例:
- $post_data = array ("category" => "9");
- echo postCurl('http://fity.cn/category.php',$post_data);
- //CURL函數(shù)--POST方式請(qǐng)求資源
- function postCurl($api_url, $post_data){
- $ch = curl_init(); // 初始化CURL句柄
- curl_setopt($ch, CURLOPT_URL, $api_url); // 設(shè)置訪(fǎng)問(wèn)的url地址
- curl_setopt($ch, CURLOPT_TIMEOUT, 35); // 設(shè)置超時(shí)
- curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15); // 等待的時(shí)間,如果設(shè)置為0,則不等待
- curl_setopt($ch, CURLOPT_HEADER, false); // 設(shè)定是否輸出頁(yè)面內(nèi)容
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 設(shè)定是否顯示頭信息
- curl_setopt($ch, CURLOPT_POST, true); // post數(shù)據(jù)
- curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);// post的變量
- curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"); // 模擬瀏覽器頭信息
- curl_setopt($ch, CURLOPT_REFERER, "http://www.x.com"); // 偽造來(lái)源地址
- $data = curl_exec($ch);
- curl_close($ch);
- if ($data) {
- return $data;
- } else {
- return false;
- }
- }
file_get_contents post方式獲取數(shù)據(jù):
- $postdata = array ('category' => 9);
- $postdata = http_build_query($postdata);
- $opts = array (
- 'http' => array (
- 'method' => 'POST',
- 'content' => $postdata
- ) //Vevb.com
- );
- $context = stream_context_create($opts);
- $html = file_get_contents('http://fity.cn/category.php', false, $context);
- echo $html;
新聞熱點(diǎn)
疑難解答