1.cURL介紹
cURL 是一個(gè)利用URL語法規(guī)定來傳輸文件和數(shù)據(jù)的工具,支持很多協(xié)議,如HTTP、FTP、TELNET等。最爽的是,PHP也支持 cURL 庫。本文將介紹 cURL 的一些高級(jí)特性,以及在PHP中如何運(yùn)用它。
2.基本結(jié)構(gòu)
在學(xué)習(xí)更為復(fù)雜的功能之前,先來看一下在PHP中建立cURL請(qǐng)求的基本步驟:
(1)初始化
curl_init()
(2)設(shè)置變量
curl_setopt() 。最為重要,一切玄妙均在此。有一長串cURL參數(shù)可供設(shè)置,它們能指定URL請(qǐng)求的各個(gè)細(xì)節(jié)。要一次性全部看完并理解可能比較困難,所以今天我們只試一下那些更常用也更有用的選項(xiàng)。
(3)執(zhí)行并獲取結(jié)果
curl_exec()
(4)釋放cURL句柄
curl_close()
3.cURL實(shí)現(xiàn)Get和Post
3.1 Get方式實(shí)現(xiàn)
復(fù)制代碼 代碼如下:
//初始化
$ch = curl_init();
//設(shè)置選項(xiàng),包括URL
curl_setopt($ch, CURLOPT_URL, "http://www.survivalescaperooms.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
//執(zhí)行并獲取HTML文檔內(nèi)容
$output = curl_exec($ch);
//釋放curl句柄
curl_close($ch);
//打印獲得的數(shù)據(jù)
print_r($output);
復(fù)制代碼 代碼如下:
$url = "http://localhost/web_services.php";
$post_data = array ("username" => "bob","key" => "12345");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// post數(shù)據(jù)
curl_setopt($ch, CURLOPT_POST, 1);
// post的變量
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
curl_close($ch);
//打印獲得的數(shù)據(jù)
print_r($output);
$output_array = json_decode($output,true);
如果使用json_decode($output)解析的話,將會(huì)得到object類型的數(shù)據(jù)。
新聞熱點(diǎn)
疑難解答