Home > database >  how to decode JSON data from API with PHP 7.4
how to decode JSON data from API with PHP 7.4

Time:10-16

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);```

CodePudding user response:

you must specify curl CURLOPT_RETURNTRANSFER so that it can return the value as a string

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://pokeapi.co/api/v2/generation/?limit=2',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
));

$output = curl_exec($curl);

curl_close($curl);

$decoded = json_decode($output);

echo $decoded->count;

?>

Here more options that can help you https://www.php.net/manual/en/function.curl-setopt.php

  • Related