php curl
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
1.cURL介紹
cURL 是一個(gè)利用URL語法規(guī)定來傳輸文件和數(shù)據(jù)的工具,支持很多協(xié)議,如HTTP、FTP、TELNET等。最爽的是,PHP也支持 cURL 庫。本文將介紹 cURL 的一些高級特性,以及在PHP中如何運(yùn)用它。
2.基本結(jié)構(gòu)
在學(xué)習(xí)更為復(fù)雜的功能之前,先來看一下在PHP中建立cURL請求的基本步驟:
(1)初始化
curl_init()
(2)設(shè)置變量
curl_setopt() 。最為重要,一切玄妙均在此。有一長串cURL參數(shù)可供設(shè)置,它們能指定URL請求的各個(gè)細(xì)節(jié)。要一次性全部看完并理解可能比較困難,所以今天我們只試一下那些更常用也更有用的選項(xiàng)。
(3)執(zhí)行并獲取結(jié)果
curl_exec()
(4)釋放cURL句柄
curl_close()
3.cURL實(shí)現(xiàn)Get和Post
Get方式實(shí)現(xiàn)
//初始化
$ch = curl_init();
//設(shè)置選項(xiàng),包括URL
curl_setopt($ch, CURLOPT_URL, "http://www.jb51.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);
Post方式實(shí)現(xiàn)
$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);
以上方式獲取到的數(shù)據(jù)是json格式的,使用json_decode函數(shù)解釋成數(shù)組。
$output_array = json_decode($output,true);
如果使用json_decode($output)解析的話,將會得到object類型的數(shù)據(jù)。
轉(zhuǎn)載于:https://my.oschina.net/u/3359663/blog/1580844
總結(jié)
- 上一篇: Javascript 创建对象方法的总结
- 下一篇: 一次thinkphp框架 success