php - 通过数据库循环向 API 发送 CURL 请求
问题描述
我一直在尝试从 mysql 数据库表中选择值(学生数据)并循环访问数据库以使用 PHP CURL Post 请求发送到 API,但它不起作用。
这是 API 正文:
{
"students":[
{
"admissionNumber": "2010",
"class":"js one"
},
{
"admissionNumber": "2020",
"class":"ss one"
}
],
"appDomain":"www.schooldomain.com"
}
我要发送的参数是“admissionNumber”和“class”参数,而“appDomain”对所有参数都是一样的。这是我的代码:
if(isset($_POST['submit'])){
$body = "success";
$info = "yes";
class SendDATA
{
private $url = 'https://url-of-the-endpoint';
private $username = '';
private $appDomain = 'http://schooldomain.com/';
// public function to commit the send
public function send($admNo,$class)
{
$url_array= array('admissionNumber'=>$admNo,'class'=>$class,'appDomain'=>$this-> appDomain);
$url_string = $data = http_build_query($url_array);
// using the curl library to make the request
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $this->url);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $url_string);
curl_setopt($curlHandle, CURLOPT_POST, 1);
$responseBody = curl_exec($curlHandle);
$responseInfo = curl_getinfo($curlHandle);
curl_close($curlHandle);
return $this->handleResponse($responseBody,$responseInfo);
}
private function handleResponse($body,$info)
{
if ($info['http_code']==200){ // successful submission
$xml_obj = simplexml_load_string($body);
// extract
return true;
}
else{
// error handling
return false;
}
}
}
$sms = new SendDATA();
$result = mysqli_query( $mysqli, "SELECT * FROM school_kids");
while ($row = mysqli_fetch_array($result)) {
$admNo = $row['admNo'];
$class = $row['class'];
$sms->send($admNo,$class,"header");
echo $admNo. " ".$class;
}
}
解决方案
这个问题相当不清楚。当您说“这是 API 主体”时,我认为这个 JSON 片段是 REST API 所https://url-of-the-endpoint
期望的。如果是这样,那么您构建的请求正文是错误的。http_build_query
创建一个 URL 编码的表单数据块(如key=value&anotherKey=another_value
),而不是 JSON。对于 JSON,这就是您想要的:
$data = array('students' => array
(
array('admissionNumber' => $admNo, 'class' => $class)
),
'appDomain':$this->appDomain
);
$url_string = $data = json_encode($data);
此外,您可能希望从响应中删除 HTTP 标头:
curl_setopt($curlHandle, CURLOPT_HEADER, false);
推荐阅读
- laravel - Laravel DB::raw 防止没有 setBindings 的 SQL 注入
- node.js - discord.js 中的 node-fetch 无法读取属性
- docker - 如何在 Kubernetes 的 elasticsearch 数据目录上做 chown 1000:1000
- powershell - 如何重新编号大量文件?
- stata - 使用 tabout 命令时结果不一致
- oracle - 只更新一定数量的记录
- dart - 无法安装 dart-sdk?
- python - 如何读取 yaml 文件中的标题?
- python - 将图像分割类输出转换为张量流中的图像
- css - Flexbox 未对齐