Home > database >  PHP cURL with CURLOPT_POSTFIELDS in json format
PHP cURL with CURLOPT_POSTFIELDS in json format

Time:10-22

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!

CodePudding user response:

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;
  • Related