Hi guys i have been working with an api and they return a response like this. I am really confused on here cause i have tried accessing it like any other json data but it’s returning an attempt to read error
[{
"service": 1,
"name": "Followers",
"type": "Default",
"category": "First Category",
"rate": "0.90",
"min": "50",
"max": "10000",
"refill": true,
"cancel": true
},
{
"service": 2,
"name": "Comments",
"type": "Custom Comments",
"category": "Second Category",
"rate": "8",
"min": "10",
"max": "1500",
"refill": false,
"cancel": true
}
]
this is my api request
$api_key = "myapikey";
$link = "httpsaddresshere";
$params = [
'key' => $api_key,
'action' => 'services'
];
$url = curl_init($link);
curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url, CURLOPT_POST, 1);
curl_setopt($url, CURLOPT_POSTFIELDS, $params);
$exec = curl_exec($url);
$result = json_decode($exec);
echo $result->name;
Api is working fine i am seeing result when i use var_dump; but it returns an error trying to access the data
2
Answers
This is because the JSON returned is an array of objects.
Thus, while passing it into
json_decode
you would get the array of objects:Doing this:
print_r($result);
would produce an output like:Thus to access it you should replace:
$result->name
with$result{0}->name
Or better if:
Would convert it into an array, thus access it as:
Just iterate on the result and get the response:
You can use
and the can access the array values by their key name like