1

I am using an API using cURL in PHP, and I need to get the value "responses" from some JSON that it returns, but everytime I try, it just returns the entire array of JSON. Here is my code so far for the API:

<?php
    $url = 'https://devman.kuki.ai/atalk';
     
    $curl = curl_init();
     
    $fields = array(
        'botkey' => '41c131bcce47671608b684cae353c7c53c6ad32dea6f92d58c316c9a0a5635d4',
        'input' => 'WHat is your name?'
    );
     
    $fields_string = http_build_query($fields);
     
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, TRUE);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $fields_string);
     
    $data = curl_exec($curl);
    
    curl_close($curl);

?>

Adding this code:

 url_setopt($curl, CURLOPT_RETURNTRANSFER, true);
 $data = curl_exec($curl);
 $jsn =  json_decode($data,1);
 echo "Response= " . $jsn['responses'][0] . "\n\n";
 var_export($jsn);
 echo "\n\n$data";
 curl_close($curl);

Will give you:

Response= My name is Kuki.

array (
  'status' => 'ok',
  'responses' => 
  array (
    0 => 'My name is Kuki.',
  ),
  'sessionid' => 3771193866,
  'channel' => 56,
  'client_name' => 'uuiprod-kdp5f6bce4a8268a350-user-0311',
)

{ "status": "ok", "responses": ["My name is Kuki."], "sessionid": 3771193866 , "channel": 56 , "client_name": "uuiprod-kdp5f6bce4a8268a350-user-0311"}
Misunderstood
  • 5,534
  • 1
  • 18
  • 25
Jake StBu
  • 31
  • 4
  • How are you getting anything? You don't enable the `CURLOPT_RETURNTRANSFER` option. – Barmar Oct 03 '22 at 23:59
  • Thanks for the free API key. You're going to want to assume that everyone on the internet now knows it and have it cancelled/reissued. Editing/deleting your question does not significantly impact anyone's ability to see it. – Sammitch Oct 04 '22 at 00:30
  • @Barmar It works without the `CURLOPT_RETURNTRANSFER`. Kinda. Without it, a "1" is appended to the JSON string and json_decode() fails unless I trim the "1". With the option, the json_decode() works fine, no trim needed. – Misunderstood Oct 07 '22 at 04:26
  • @Misunderstood Right, it's just returning `true` or `false`, and `true` converts to the string `1`, which is valid JSON. But if they actually want to get the API response, it's not really working. – Barmar Oct 07 '22 at 15:16

0 Answers0