likes
comments
collection
share

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

作者站长头像
站长
· 阅读数 20
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;

參考https://ianakaberlin.medium.c...

转载自:https://segmentfault.com/a/1190000018733979
评论
请登录