php 请求api的参数为数组怎么组装php代码
- 使用http_build_query函数将数组转换为URL编码的字符串
例如,如果有以下数组:
$params = array(
'name' => 'John',
'age' => 25,
'city' => 'New York'
);
可以使用http_build_query函数将其转换为URL编码的字符串:
$query = http_build_query($params);
// $query的值为 "name=John&age=25&city=New+York"
- 将URL编码的字符串作为请求参数
使用curl发送请求时,可以将URL编码的字符串作为请求参数发送:
$url = 'http://example.com/api';
$ch = curl_init($url.'?'.$query); // 注意要加上问号
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
- 将数组转换为JSON字符串
如果API要求请求参数为JSON格式,可以使用json_encode函数将数组转换为JSON字符串:
$json = json_encode($params);
// $json的值为 '{"name":"John","age":25,"city":"New York"}'
- 将JSON字符串作为请求参数
使用curl发送请求时,可以将JSON字符串作为请求参数发送:
$url = 'http://example.com/api';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
``
原文地址: https://www.cveoy.top/t/topic/fJ3U 著作权归作者所有。请勿转载和采集!