1.cURL介紹
cURL 是一個利用URL語法規(guī)定來傳輸文件和數(shù)據(jù)的工具厢呵,支持很多協(xié)議,如HTTP蝶缀、FTP丹喻、TELNET等。最爽的是翁都,PHP也支持 cURL 庫碍论。本文將介紹 cURL 的一些高級特性,以及在PHP中如何運用它柄慰。
2.基本結構
在學習更為復雜的功能之前鳍悠,先來看一下在PHP中建立cURL請求的基本步驟:
(1)初始化
php
curl_init()
(2)設置變量
php
curl_setopt()
最為重要,一切玄妙均在此坐搔。有一長串cURL參數(shù)可供設置藏研,它們能指定URL請求的各個細節(jié)。要一次性全部看完并理解可能比較困難概行,所以今天我們只試一下那些更常用也更有用的選項蠢挡。
(3)執(zhí)行并獲取結果
php
curl_exec()
(4)釋放cURL句柄
php
curl_close()
3.cURL實現(xiàn)Get和Post
3.1 Get方式實現(xiàn)
php
//初始化
$ch = curl_init();
//設置選項,包括URL
curl_setopt($ch, CURLOPT_URL, "http://zixuephp.net");
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);
3.2 Post方式實現(xiàn)
php
$url = "http://zixuephp.net/index.html";
$post_data = array ("name" => "username","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);
以上方式獲取到的數(shù)據(jù)是json格式的凳忙,使用json_decode函數(shù)解釋成數(shù)組业踏。$output_array = json_decode($output,true);如果使用json_decode($output)解析的話,將會得到object類型的數(shù)據(jù)涧卵。