鍍金池/ 問(wèn)答/PHP  Linux  網(wǎng)絡(luò)安全  HTML/ php curl 如何做多個(gè)?

php curl 如何做多個(gè)?

$data = array(
    "manager" => $login_acc,
    "password" => $login_pas
  );
  $data_string = json_encode($data);
  $ch = curl_init($api_signin);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
  curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      'Content-Type: application/json',
      'Content-Length: ' . strlen($data_string))
  );
  curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
  $result = curl_exec($ch);
  curl_close($ch);
  $data = json_decode($result);

因?yàn)榘l(fā)現(xiàn)有很多需求需要用到curl
但如果每個(gè)都是這麼長(zhǎng)的格式會(huì)很可觀
想問(wèn)問(wèn)有沒(méi)有「多個(gè)」但可能某一部分只要寫一次就行的可能?

回答
編輯回答
敢試
Guzzle是一個(gè)PHP的HTTP客戶端,用來(lái)輕而易舉地發(fā)送請(qǐng)求,并集成到我們的WEB服務(wù)上。

中文文檔
英文文檔
github

如果你不喜歡上面的擴(kuò)展那么你可以將代碼中重復(fù)的部分提取出來(lái),寫成一個(gè)公用的方法,向里面?zhèn)鬟f參數(shù),返回你所需的參數(shù)

2018年9月21日 16:23
編輯回答
筱饞貓

composer

rmccue/requests

$headers = array('Accept' => 'application/json');
$options = array('auth' => array('user', 'pass'));
$request = Requests::get('https://api.github.com/gists', $headers, $options);

var_dump($request->status_code);
// int(200)

var_dump($request->headers['content-type']);
// string(31) "application/json; charset=utf-8"

var_dump($request->body);

API異常簡(jiǎn)單,而且是靜態(tài)方法調(diào)用

2018年2月5日 12:35