curl可以說是php裡一個非常強大的功能,每個php程式員都應該學習並熟悉curl,使用curl前確保你的php_curl擴充已經開啟。
一、curl使用
例如:我們採集深圳智聯招聘上PHP招聘的第一頁資訊複製代碼 代碼如下:$url='http://sou.zhaopin.com/jobs/searchresult.ashx?jl=%E6%B7%B1%E5%9C%B3&kw=php&sm=0&p=1';
//初始化
$ch = curl_init();
//設定選項,包括URL
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//不自動輸出內容
curl_setopt($ch, CURLOPT_HEADER, 0);//不返回頭部資訊
//執行curl
$output = curl_exec($ch);
//錯誤提示
if(curl_exec($ch) === false){
die(curl_error($ch));
}
//釋放curl控制代碼
curl_close($ch);
header('Content-type: text/html; charset=utf-8');
echo $output;
當然我們必須對返回的資料使用<<Regex>>處理,找出我們想要的那一部分,然後根據你的需要把資料填充到你網站裡複製代碼 代碼如下://職位名稱
preg_match_all('/<td class="Jobname">.*?<a\s*href="(.*?)"\starget="_blank">(.*?)<\/a>/s', $output, $title);
$title[1];//連結
$title[2];//標題
//公司名稱
preg_match_all('/<td class="Companyname">.*?<a href="(.*?)"\starget="_blank">(.*?)<\/a>/s', $output, $company);
$company[1];//連結
$company[2];//名字
//工作地點
preg_match_all('/<td class="Companyaddress">\s*(.*?)\s*<\/td>/s', $output, $address);
$address[1];//地點
//發布日期
preg_match_all('/<td class="releasetime">\s*(.*?)\s*<\/td>/s', $output, $time);
$time[1];//時間
var_dump($time[1]);
二、常用功能
curl的核心是通過設定各種選項來達到各種功能,這裡我們介紹幾種常用的選項。
1.post資料
複製代碼 代碼如下:$post=array(
'uid'=>'test',
'pwd'=>'curl123'
);
curl_setopt($ch, CURLOPT_POST, 1);//設定為POST方式
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));//POST資料
2.cookie
複製代碼 代碼如下:$savefile=dirname(__FILE__).'save.txt';
$getfile=dirname(__FILE__).'get.txt';
//可以分開使用
curl_setopt($ch, CURLOPT_COOKIEJAR, $savefile); //儲存
curl_setopt($ch, CURLOPT_COOKIEFILE, $getfile); //讀取
3.偽造IP、來路
複製代碼 代碼如下:curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:8.8.8.8', 'CLIENT-IP:8.8.8.8'));//構造IP
curl_setopt($ch, CURLOPT_REFERER, "http://www.baidu.com");//構造來路
curl_setopt選項大全,詳見PHP手冊:http://www.php.net/manual/zh/function.curl-setopt.php
三、多線程
官方樣本複製代碼 代碼如下:// 建立一對cURL資源
$ch1 = curl_init();
$ch2 = curl_init();
// 設定URL和相應的選項
curl_setopt($ch1, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);
// 建立批處理cURL控制代碼
$mh = curl_multi_init();
// 增加2個控制代碼
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);
$running=null;
// 執行批處理控制代碼
do {
usleep(10000);
curl_multi_exec($mh,$running);
} while ($running > 0);
// 關閉全部控制代碼
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);