How to store curl response in a variable in PHP?
How to store curl response in a variable in PHP?
I am working on an API. When I make request curl print the response on browser. So, my question is how to store response in variable? and How to insert it into database?
<?php
//API Url
$url = 'http://114.143.206.69:803/StandardForwardStagingService.svc/GetAWBNumberGeneratedSeries';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = array(
"BusinessUnit" => "ECOM",
"ServiceType" => "FORWARD",
"BatchID" => "Jopu7E9821"
);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','XBKey:******'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Execute the request
$result = curl_exec($ch);
$status = curl_getinfo($ch);
It's already storing data in
$result
. Also use json format to store whole response in database.– Lovepreet Singh
2 mins ago
$result
1 Answer
1
As described in the documentation ...
Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.
So your code has to look like this
$result = curl_exec($ch);
// output it on the screen
echo "<pre>";
var_dump($result);
echo "</pre>";
// insert into database
$sql = "INSERT INTO table (column1, column2) VALUES (:result1, :result2)";
$pdo = new PDO(...);
$stmt = $pdo->prepare($sql);
$stmt->execute([
':result1' => $result['bla'],
':result2' => $result['blubb'],
]);
That should be all you have to do.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
You will get response in $result variable. You can just do print_r($result); to check what coming in response and use that to store in db.
– Jasmin Mistry
2 mins ago