PHP CURL Req. Json Format And Using Variables
How to use variable on postfields json type on php ?
I set deger variable 123 but curl don't send this data please help me
<?php
$deger=123;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://serviceurl',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{
"iprocessnumber": "$deger",
"activationStatus": "SUCCESS",
"code": "100",
"message": "Test mesaj?�"
}',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
?>
Answer
Solution:
You could use that CURLOPT_POSTFIELDS
to be pointed to a JSON encoded array.
$postFields
holds the encoded fields.
<?php
$deger=123;
$curl = curl_init();
$postFields= [
"iprocessnumber"=>$deger,
"activationStatus"=>"SUCCESS",
"code"=>"100",
"message"=>"Test mesaj?�"
];
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://serviceurl',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>json_encode($postFields),
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
?>
Hope this helps.
Source