PHP cURL with CURLOPT_POSTFIELDS in json format

js4nwp54  于 2022-10-22  发布在  PHP
关注(0)|答案(1)|浏览(213)

I'm not quite familiar with cURL and been struggling on this issue though.
I'm sending a post request by using cURL and the data field is in json format.
My coding:

$ch = curl_init($url);
$authorization = "Authorization: Bearer ".$token;
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = "test";

$data = <<<DATA
{
    "shop_id": 1231232,
    "message": "test"
}
DATA;

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

What I'm trying to achieve here is to replace the "message" value with php variable $response . What is the correct way to do that? Thank you!

krugob8w

krugob8w1#

This has nothing to do with cURL specifically, it's about including variables in a data structure or string.
My first piece of advice would be: don't generate JSON string literals in your code, it's fiddly and potentially error-prone. Build a suitable PHP data structure and then use json_encode() to reliably turn it into a valid JSON string.
As it happens, following this approach also makes your current requirement very easy to achieve using basic PHP:

$data = [
  "shop_id" => 1231232,
  "message" => $response
];

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

P.S. In a different scenario (e.g. not trying to generate JSON) where using heredoc would be more appropriate, the solution is also simple, you just replace the hard-coded value with the variable:

$data = <<<DATA
{
    "shop_id": 1231232,
    "message": $response
}
DATA;

相关问题