我一直在尝试从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;
}
}
发布于 2020-06-18 10:18:42
这个问题相当不清楚;当您说“这就是API body”时,我假设这个JSON片段就是https://url-of-the-endpoint
的REST API所期望的。如果是这样,那么您构建的请求正文就是错误的。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);
https://stackoverflow.com/questions/62440868
复制相似问题