当前位置: 首页 > 后端技术 > PHP

php使用Curl向对方传递json数据并显示对方返回的json(Json格式-API连接-HttpRequest)

时间:2023-03-29 16:10:15 PHP

函数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);returnjson_decode($result);}将下面的数据转成json格式传给对应的$data=array("id"=>$id,"field"=>$field);$data=httpRequest('',json_encode($data));echo$data->打印出对方返回的jsonkey和value{'message'};如果对方返回的是json数组,可以用foreach循环打印出来,对方返回多少笔就打印多少。foreach($dataas$value){echo$value['message'];}可以使用sizeof查看对象的长度,轻松做出判断echosizeof($data);//int如果对方的response不是json,直接传body,改returnjson_decode($result);在上面的函数中Return$result;然后直接打印出echo$data;参考https://ianakaberlin.medium.c...