0

I use the curl code below to get and display json file contents and everything works fine with the code below

when I print the json result with

$json = json_decode($response);
 print_r($json);

Am having the result displayed in this format

stdClass Object ( [id] => 123
[food] => Array ( [0] => rice ) 

[buyer] => AkwaezeOby 

[amount] => 2000 ) 

Now am trying to get values for food and buyer only and I have tried this below but cannot get it to work

print_r($json["food"][0]);
print_r($json["buyer"]);

or

echo $json["food"][0];
echo $json["buyer"];

Below is the working code for data display. can someone help me to get values for food and buyer only. thanks

$curl = curl_init();

curl_setopt_array($curl, array( 
CURLOPT_URL => "myapi.com", 
CURLOPT_RETURNTRANSFER => true, 
CURLOPT_ENCODING => "", 
CURLOPT_MAXREDIRS => 10, 
CURLOPT_TIMEOUT => 30, 
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, 
CURLOPT_CUSTOMREQUEST => "GET", 
//CURLOPT_POSTFIELDS => "$data", 
CURLOPT_HTTPHEADER => array( 
"accept: application/json", 
"authorization: --my number goes here--", 
"content-type: application/json; charset=utf-8" 
), 
));

$response = curl_exec($curl); 
$err = curl_error($curl);

curl_close($curl);


 $json = json_decode($response);

print_r($json);
akwaeze
  • 71
  • 7
  • 2
    Possible duplicate of [How do I extract data from JSON with PHP?](https://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php) – user3942918 Jul 23 '17 at 21:32
  • Can you please paste the raw json from ```$response```? It'll help us answer the question. (```print_r($response)```) Thanks. – PressingOnAlways Jul 23 '17 at 21:32
  • stdClass Object ( [id] => 123 [food] => Array ( [0] => rice ) [buyer] => AkwaezeOby [amount] => 2000 ) – akwaeze Jul 23 '17 at 21:39

1 Answers1

1

a possible solution could be using this

$json = json_decode($response, true);

From Docs the second parameter: When TRUE, returned objects will be converted into associative arrays.

Daisen Sekai
  • 143
  • 7