欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

php curl的深入解析

 更新時間:2013年06月02日 15:18:59   作者:  
本篇文章是對php curl的使用就行了詳細的分析介紹,需要的朋友參考下
curl可以說是php里一個非常強大的功能,每個php程序員都應(yīng)該學(xué)習(xí)并熟悉curl,使用curl前確保你的php_curl擴展已經(jīng)開啟。

一、curl使用
例如:我們采集深圳智聯(lián)招聘上PHP招聘的第一頁信息
復(fù)制代碼 代碼如下:

$url='http://sou.zhaopin.com/jobs/searchresult.ashx?jl=%E6%B7%B1%E5%9C%B3&kw=php&sm=0&p=1';
//初始化
$ch = curl_init();
//設(shè)置選項,包括URL
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//不自動輸出內(nèi)容
curl_setopt($ch, CURLOPT_HEADER, 0);//不返回頭部信息
//執(zhí)行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;

當(dāng)然我們必須對返回的數(shù)據(jù)使用<<正則表達式>>處理,找出我們想要的那一部分,然后根據(jù)你的需要把數(shù)據(jù)填充到你網(wǎng)站里
復(fù)制代碼 代碼如下:

//職位名稱
preg_match_all('/<td class="Jobname">.*?<a\s*href="(.*?)"\starget="_blank">(.*?)<\/a>/s', $output, $title);
$title[1];//鏈接
$title[2];//標(biāo)題
//公司名稱
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];//地點
//發(fā)布日期
preg_match_all('/<td class="releasetime">\s*(.*?)\s*<\/td>/s', $output, $time);
$time[1];//時間
var_dump($time[1]);

二、常用功能
curl的核心是通過設(shè)置各種選項來達到各種功能,這里我們介紹幾種常用的選項。
1.post數(shù)據(jù)
復(fù)制代碼 代碼如下:

$post=array(
'uid'=>'test',
'pwd'=>'curl123'
);
curl_setopt($ch, CURLOPT_POST, 1);//設(shè)置為POST方式
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));//POST數(shù)據(jù)

2.cookie
復(fù)制代碼 代碼如下:

$savefile=dirname(__FILE__).'save.txt';
$getfile=dirname(__FILE__).'get.txt';
//可以分開使用
curl_setopt($ch, CURLOPT_COOKIEJAR, $savefile); //保存 
curl_setopt($ch, CURLOPT_COOKIEFILE, $getfile); //讀取

3.偽造IP、來路
復(fù)制代碼 代碼如下:

curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:8.8.8.8', 'CLIENT-IP:8.8.8.8'));//構(gòu)造IP 
curl_setopt($ch, CURLOPT_REFERER, "http://www.baidu.com");//構(gòu)造來路 

curl_setopt選項大全,詳見PHP手冊:http://www.php.net/manual/zh/function.curl-setopt.php
三、多線程
官方示例
復(fù)制代碼 代碼如下:

// 創(chuàng)建一對cURL資源
$ch1 = curl_init();
$ch2 = curl_init();
// 設(shè)置URL和相應(yīng)的選項
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);
// 創(chuàng)建批處理cURL句柄
$mh = curl_multi_init();
// 增加2個句柄
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);
$running=null;
// 執(zhí)行批處理句柄
do {
    usleep(10000);
    curl_multi_exec($mh,$running);
} while ($running > 0);
// 關(guān)閉全部句柄
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

相關(guān)文章

最新評論