php 使用Curl傳遞json資料給對方及顯示對方回傳的json(Json格式/ API串接/ HttpRequest)

本教學使用環境介紹
伺服器端:Ubuntu 18.04 LTS
資料庫:Mariadb 10.1.34(Mysql)
語言版本:php 7.3
本機端:MacOS High Sierra

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>

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

要印出對方回的 json key and value 內容時

echo $data->{'message'};

如果對方回的是json array,使用foreach接應即可
就能夠印出迴圈,對方回傳多少筆就印多少筆

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

可以使用sizeof查看object的長度,輕鬆做判斷

echo sizeof($data); // int

如果對方回的不是json只是直接傳 body 過來
將上面的function中的

return json_decode($result);

改爲

return $result;

然後直接印出即可

echo $data;

Line ID:ianmac
QQ:1258554508

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章