Как сохранить ответ curl в переменной в PHP? - PullRequest
0 голосов
/ 03 июля 2018

Я работаю над API. Когда я делаю запрос curl распечатать ответ в браузере. Итак, мой вопрос, как хранить ответ в переменной? и как вставить его в базу данных?

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

Мой ответ после var_dump ($ result)

1 Ответ

0 голосов
/ 03 июля 2018

Как описано в документации ...

Возвращает TRUE в случае успеха или FALSE в случае неудачи. Однако, если установлена ​​опция CURLOPT_RETURNTRANSFER, она вернет результат в случае успеха, FALSE в случае ошибки.

Итак, ваш код должен выглядеть так

<code>$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 "
"; // вставить в базу данных (если $ result является массивом) $ sql = "INSERT INTO table (column1, column2) VALUES (: result1,: result2)"; $ pdo = new \ PDO (...); $ stmt = $ pdo-> prepare ($ sql); $ Stmt-> выполнить ([ ': result1' => $ result ['bla'], ': result2' => $ result ['blubb'], ]);

Это должно быть все, что вам нужно сделать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...