如何在 curl post 中使用变量?

How to use variables in a curl post?

我正在创建一个 php 脚本,它将使用 curl 在我的 Parse 数据库中添加一个新行。我很难将变量添加到我的 setopt 语句中。如果有人能引导我朝着正确的方向前进,那么我将不胜感激。

这是我的 PHP 执行 curl 语句的代码:

//curl commands to send information to parse
  $ch = curl_init('https://api.parse.com/1/classes/className');

curl_setopt($ch,CURLOPT_HTTPHEADER,
    array('X-Parse-Application-Id:secret1',
    'X-Parse-REST-API-Key:secret2',
    'Content-Type: application/json'));

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);


curl_setopt($ch, CURLOPT_POSTFIELDS,  "{\"Name\":\"$deviceName\"}" );

echo curl_exec($ch);
curl_close($ch);

我得到的回复是:

{"code":107,"error":"invalid JSON"}

提前致谢!

有什么理由不能在发送数据之前对数组进行编码吗?

例如(未经测试):

$arr = [ "Name" => $deviceName ];
$arr_string = json_encode($arr);

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($arr_string)
));

curl_setopt($ch, CURLOPT_POSTFIELDS, $arr_string );