Reputation: 71
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);
Upvotes: 0
Views: 1667
Reputation: 163
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.
Upvotes: 1