CURLOPT_POSTFIELDS
不接受json_encode,但是如果我直接在CURLOPT_POSTFIELDS
中写入json(如果已输入)
这将返回错误
{“错误”:“ bad_request”,“原因”:“请求正文必须是JSON对象”}
$bd = "fiscont_db_catalogo_cuentas";
$ch = curl_init();
$document ='{"docs":[{"key":"baz","name":"bazzel"},{"key":"bar","name":"barry"}]}';
$json = json_encode($document);
echo $json;
curl_setopt($ch, CURLOPT_URL, 'http://127.0.0.1:5984/'.$bd.'/_bulk_docs');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); /* or PUT */
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'Accept: */*'
));
curl_setopt($ch, CURLOPT_USERPWD, 'root:addc1243c');
$response = curl_exec($ch);
echo $response;
curl_close($ch);
但这返回了:
[{“ ok”:true,“ id”:“ 8b3c672ffd4b8dcd7da313e9e9011243”,“ rev”:“ 1-f5f3f3e496c72307975a69c73fd53d42”},{“ ok”:true,“ id”:“ 8b3c672ffd4b8a” 90“,” 1-8ad0e70d5e6edd474ec190eac2376bde“}]
$bd = "fiscont_db_catalogo_cuentas";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://127.0.0.1:5984/'.$bd.'/_bulk_docs');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); /* or PUT */
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"docs\":[{\"key\":\"baz\",\"name\":\"bazzel\"},{\"key\":\"bar\",\"name\":\"barry\"}]}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'Accept: */*'
));
curl_setopt($ch, CURLOPT_USERPWD, 'root:addc1243c');
$response = curl_exec($ch);
echo $response;
curl_close($ch);
答案 0 :(得分:0)
json_encode
将数组或对象作为参数。在您的示例中,您将JSON字符串编码为没有意义的JSON。
如果您用以下内容替换行:
$document =['docs' => [['key'=>'baz','name'=>'bazzel'],['key'=>'bar','name'=>'barry']];
它将正确地将您的PHP关联数组转换为JSON。