Reputation: 74
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);
My Response after var_dump($result)
Upvotes: 1
Views: 3154
Reputation: 5119
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);
// as you mentioned the response is a json string (screenshot)
$decoded_result = json_decode($result);
// output it on the screen
echo "<pre>";
var_dump($result);
echo "</pre>";
// insert into database (in case $result is an array)
$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.
Upvotes: 1