【发布时间】:2018-09-14 20:33:33
【问题描述】:
我正在使用 PHP 通过 curl 发送 HTML 发布请求。我想在 URL 处向现有 JSON 数组添加更多数据。如果我发布请求,它会替换数据还是将其添加到现有数组中?目前,我正在写:
// Setup cURL
$ch = curl_init('http://www.barn-door.co.uk/wp-json/geodir/v1/farms');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'Authorization: '.$authToken,
'Content-Type: application/json'
),
CURLOPT_POSTFIELDS => json_encode($postData)
));
// Send the request
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
die(curl_error($ch));
}
// Decode the response
$responseData = json_decode($response, TRUE);
// Print the date from the response
echo $responseData['published'];
其中 $postData 是我的 json 格式数据。
谢谢:)
【问题讨论】:
-
替换当前数据。只需在编码和设置之前修改
$data-array。 -
注意: 这不是您使用 cURL 发送 json 的方式。来自有关 CURL_POSTFIELDS 的手册:“此参数可以作为 urlencoded 字符串(如 'para1=val1¶2=val2&...')或作为字段名称作为键和字段数据作为值的数组传递。”我>。您应该在正文中发送 json 字符串,并确保将内容类型设置为
application/json。