一段简单的PHP向API接口发出请求代码示例,使用了curl请求方式。
首先创建了一个包含API端点URL及其参数的关联数组$data。
接着设置了一些cURL选项,包括将请求设置为post方法,并将数据编码为URL编码格式。
使用curl_exec()执行请求并获取响应。
我们还检查了是否有任何错误。
最后,我们关闭了cURL资源。
<?php
$url = "https://api.example.com/endpoint";
$data = array('param1' => 'value1', 'param2' => 'value2');
// Set up cURL options
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
// Execute the request and get the response
$response = curl_exec($ch);
// Check for any errors
if(curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
} else {
// Print the response
echo $response;
}
// Close the cURL resource
curl_close($ch);
?>
