0

I have following php api to fetch some third party json data.

<?php

$url = 'https://players-facts-api.herokuapp.com/api/v1/resources/players?number=1'; // path to your JSON file
$imgUrl='https://random.cricket/players.json';
$data = file_get_contents($url); // put the contents of the file into a variable
$dataImg= file_get_contents($imgUrl);
$characters = json_decode($data); // decode the JSON feed
$imgCharacters = json_decode($dataImg, true);

echo $characters[0]->fact;
echo $imgCharacters[0]->url;
print_r($imgCharacters);

?>

Here, when I run this php file, it gives me the correct output for

echo $characters[0]->fact;

But it kept giving me an error for the

echo $imgCharacters[0]->url;

The error is,

Warning: Attempt to read property "url" on null in C:\xampp\htdocs\cricinfo\player-fact-app\index.php on line 11

When I print the second array, it giving me something like follows,

Array ( [fileSizeBytes] => 285621 [url] => https://random.players/a62ccc75-2b8b-48d1-9110-b6e8d5687c07.jpg )
Arctic Fox
  • 59
  • 9
  • 2
    `$imgCharacters` is an associative array, not indexed. You want `$imgCharacters['url']` – Phil Jul 07 '22 at 06:30
  • 2
    Well your are decoding the json as array and not as an object, . So ``$imgCharacters[0]['url'];``. Or just remove the "true" from the json_decode to not decode it as array. – enricog Jul 07 '22 at 06:32
  • 1
    You use json_decode($dataImg, true); -> true => array. Remove true to have an object. Or do $imgCharacters[0]['url']; (but, I'm not sure you have an index 0 => $imgCharacters['url'];) – svgta Jul 07 '22 at 06:33

1 Answers1

1

You parsed the second array as an associative array. There is no index 0, you can access the url using the key $imgCharacters['url']. (without -> as it is not an object)

Eva
  • 11
  • 1