i connect to api with cURL and receive JSON response. cannot use PHP to parse data because of PHP error: ‘Trying to access array offset on value of type int’
i have used json_decode()
but still receive error. i have also tried decode as both array and object by setting 2nd parameter to ‘true’ and ‘false’. i have used gettype()
and received NULL
response. i am using PHP 7.4.3 but i believe this would work in older versions of PHP. how do we parse the JSON into a PHP object or array in these newer versions?
here is the JSON returned from api:
{"count":8,"next":"https://pokeapi.co/api/v2/generation/?offset=2&limit=2","previous":null,"results":[{"name":"generation-i","url":"https://pokeapi.co/api/v2/generation/1/"},{"name":"generation-ii","url":"https://pokeapi.co/api/v2/generation/2/"}]}
and here is my PHP:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://pokeapi.co/api/v2/generation/?limit=2');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$output = curl_exec($ch);
curl_close($ch);
$decoded = json_decode($output, false);
echo $decoded->count;
// i've also tried:
// $decoded = json_decode($output, true);
// echo $decoded['count']
// as well as $decoded = json_decode($output);```
2
Answers
Please note that json_decode decodes a JSON
string
So use json_decode to decode the json string and it should work:
Check this sandbox (tried:- PHP 7.4.32 works)
https://onlinephp.io/c/a48d3
Additional Information
For your case, you may simply use file_get_contents to replace curl:
you must specify curl
CURLOPT_RETURNTRANSFER
so that it can return the value as a stringHere more options that can help you
https://www.php.net/manual/en/function.curl-setopt.php