PHP cURL 主体不适用于多个数组



我需要通过PHP中的cURL发送数据。 有我的POST请求,它适用于此示例(我可以发布 1 条记录(。

$postData = array(
"username" => "email@domain.com",
"name" => "Name",
"surname" => "Surname",
'role' => 'user',
"disabled" => "false"

);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->getCurlUrl());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt_array($ch, 
array(
CURLOPT_POST => false,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'authorization: apikey '.$apikey,
'Content-Type: application/rest+json',
'pincode: '.$pincode
)
// ,CURLOPT_POSTFIELDS => json_encode($postData)
));
curl_setopt($ch, CURLOPT_POSTFIELDS , json_encode($postData));
$httpCode = curl_getinfo($ch , CURLINFO_HTTP_CODE); // this results 0 every time
$response = curl_exec($ch);
if ($response === false) $response = curl_error($ch);
return stripslashes($response);
curl_close($ch);

但是我想将数据库中的记录添加到$postDataarray但随后它停止了。

这是我的数据库数组示例:

$postData = array();
foreach ($records = $this->getRecords as $value) {
$row['username'] = $value['email'];
$row['name'] = $value['name'];
$row['surname'] = $value['surname'];
$row['role'] = 'User';
$row['disabled'] = $value['status'];
array_push($postData, $row); 

}

json数组看起来ok但我找不到错误。或者我无法发布多个数据,我需要在一个循环中添加所有内容?

我在代码中发现了一些缺陷。您说您正在发布代码,但您已设置

CURLOPT_POST => false

另外,你重复了

CURLOPT_RETURNTRANSFER => TRUE and CURLOPT_RETURNTRANSFER => 1

此外,您的 API 可能设计为接受一条记录,但您正在尝试发送多条记录。如果它设计为一次接受 1 条记录,则应使 curl 调用一个函数并调用它来代替array_push。例如:。卷曲功能($row(;

function curlfunction($postData){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->getCurlUrl());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST , 1);
curl_setopt_array($ch, CURLOPT_HTTPHEADER, array(
'authorization: apikey '.$apikey,
'Content-Type: application/rest+json',
'pincode: '.$pincode
)
);
curl_setopt($ch, CURLOPT_POSTFIELDS , json_encode($postData));
$httpCode = curl_getinfo($ch , CURLINFO_HTTP_CODE); 
$response = curl_exec($ch);
if ($response === false) $response = curl_error($ch);
curl_close($ch);
return stripslashes($response);
}

foreach ($records = $this->getRecords as $value) {
$row['username'] = $value['email'];
$row['name'] = $value['name'];
$row['surname'] = $value['surname'];
$row['role'] = 'User';
$row['disabled'] = $value['status'];
curlfunction($row); 

}

相关内容

  • 没有找到相关文章

最新更新