Read data from an external JSON API with PHP

4

I am reading a file json external (Through a URL ) and I can get the values of the first content without problem, but the second content does not, I imagine that the problem is due to the brackets "[ ] "at the beginning and end.

Any suggestions to solve it? there is some other way to get 2 or more values without repeating the code echo: ,

Example :

echo "Data: ". $json_data{"last_name"} 

and

echo "Data: ". $json_data{"age"} 

Content url_01:

{
    "name": Karl, 
    "last_name": Smith, 
    "age": 35
}   

$url = "url_01";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo "Data: ". $json_data{"name"}

It works well!

Content url_02:

[
 {
    "name": Karl, 
    "last_name": Smith, 
    "age": 35
  }
]

$url = "url_02";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo "Data: ". $json_data{"name"}];

It does not work well!

    
asked by Joe 28.07.2017 в 21:37
source

1 answer

3

What you have to differentiate is that in the first example the JSON that comes to you is a object while the second one is a array that contains an object . p>

An object is defined by brackets {} and an array by brakets [] .

Therefore, in your second example, you have a array with a single position and in which you have content an object.

With all this in mind, you could read your variable as follows:

echo "Data: ". $json_data[0]["name"];
    
answered by 28.07.2017 / 21:44
source