如何在PHP变量中存储curl响应?

时间:2018-07-03 07:03:51

标签: php curl

我正在使用API​​。当我请求卷曲时,在浏览器上打印响应。所以,我的问题是如何将响应存储在变量中?以及如何将其插入数据库?

<?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)

1 个答案:

答案 0 :(得分:0)

如文档中所述...

  

成功返回TRUE,失败返回FALSE。但是,如果设置了CURLOPT_RETURNTRANSFER选项,则成功时将返回结果,失败时将返回FALSE。

所以您的代码必须看起来像这样

$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'],
]);

那应该是您要做的所有事情。