1.cURL介紹
cURL 是一個利用URL語法規(guī)定來傳輸文件和數(shù)據(jù)的工具,支持很多協(xié)議,如HTTP、FTP、TELNET等。最爽的是,PHP也支持 cURL 庫。本文將介紹 cURL 的一些高級特性,以及在PHP中如何運用它。
2.基本結(jié)構(gòu)
在學(xué)習(xí)更為復(fù)雜的功能之前,先來看一下在PHP中建立cURL請求的基本步驟:
(1)初始化
curl_init()
(2)設(shè)置變量
curl_setopt()
最為重要,一切玄妙均在此。有一長串cURL參數(shù)可供設(shè)置,它們能指定URL請求的各個細(xì)節(jié)。要一次性全部看完并理解可能比較困難,所以今天我們只試一下那些更常用也更有用的選項。
(3)執(zhí)行并獲取結(jié)果
curl_exec()
(4)釋放cURL句柄
curl_close()
3.cURL實現(xiàn)Get和Post
3.1 Get方式實現(xiàn)
//初始化
$ch = curl_init();
//設(shè)置選項,包括URL
curl_setopt($ch, CURLOPT_URL, "http://www.nettuts.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);
3.2 Post方式實現(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ù)。
附wafer2-sdk中的Rquest庫
<?php
namespace QCloud_WeApp_SDK\Helper;
class Request {
/**
* @codeCoverageIgnore
*/
public static function get($options) {
$options['method'] = 'GET';
return self::send($options);
}
public static function jsonPost($options) {
if (isset($options['data'])) {
$options['data'] = json_encode($options['data']);
}
$options = array_merge_recursive($options, array(
'method' => 'POST',
'headers' => array('Content-Type: application/json; charset=utf-8'),
));
return self::send($options);
}
public static function send($options) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $options['method']);
curl_setopt($ch, CURLOPT_URL, $options['url']);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
if (isset($options['headers'])) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $options['headers']);
}
if (isset($options['timeout'])) {
curl_setopt($ch, CURLOPT_TIMEOUT_MS, $options['timeout']);
}
if (isset($options['data'])) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $options['data']);
}
$result = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$body = json_decode($result, TRUE);
if ($body === NULL) {
$body = $result;
}
curl_close($ch);
return compact('status', 'body');
}
}