php 使用Curl传递json资料给对方及显示对方回传的json(Json格式/ API串接/ HttpRequest)

本教学使用环境介绍
伺服器端:Ubuntu 18.04 LTS
资料库:Mariadb 10.1.34(Mysql)
语言版本:php 7.3
本机端:MacOS High Sierraphp

function httpRequest($api, $data_string) {

  $ch = curl_init($api);
  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))
  );
  $result = curl_exec($ch);
  curl_close($ch);

  return json_decode($result);
}

将如下资料变成json格式传输传给对方接应的 <https-api-url>sql

$data = array(
    "id" => $id,
    "field" => $field
);
$data = httpRequest('<https-api-url>', json_encode($data));

要印出对方回的 json key and value 内容时json

echo $data->{'message'};

若是对方回的是json array,使用foreach接应便可
就可以印出回圈,对方回传多少笔就印多少笔api

foreach ($data as $value) {
    echo $value['message'];
}

能够使用sizeof查看object的长度,轻松作判断app

echo sizeof($data); // int

若是对方回的不是json只是直接传 body 过来
将上面的function中的curl

return json_decode($result);

改成url

return $result;

而后直接印出便可code

echo $data;

Line ID:ianmac
QQ:1258554508string

相关文章
相关标签/搜索