0

I would like to retrieve information from an API with POST and be able to decode it and retrieve only the values. Here is my code:

<?php
$url = "https://exemple.com/api/search_title/";
$test = "monster";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$headers = array(
   "Accept: application/json",
   "Content-Type: application/json",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

$data = <<<DATA
{
  "title": "$test"
}
DATA;

curl_setopt($curl, CURLOPT_POSTFIELDS, $data);


$resp = curl_exec($curl);

curl_close($curl);
echo $resp;
?>

With echo $resp; the info is displayed like this:

[{"id":"12345","slug":"monster","title":"Monster"},{"id":"54321","slug":"monster-energy","title":"Monster Energy"}]

I want for example just to retrieve and decode the id and the slug like this: 12345 Monster & 54321 Monster Energy

When I try to decode and retrieve the ID value with :

$obj = json_decode($resp);
echo $obj->id;

I get:

Warning: Attempt to read property "id" on array in serc.php on line 43

and when I do :

echo $obj;

I get :

Warning: Array to string conversion in serc.php on line 43
Array

If someone can help me, thank you in advance!

falzer75
  • 3
  • 2

0 Answers0