Anna Jeanine
Anna Jeanine

Reputation: 4125

Get data for JSON file PHP

This may seem like a duplicate question, but my JSON is formatted differently than other examples I have seen. The which I am using:

$str = file_get_contents($tmp);
$json = json_decode($str, true);
$project_id = $json["project_id"];

My JSON is formatted like:

[{"project_id": 2.0, "name": "Anna", "place": "Amsterdam", "date": "31 October 2016"}]

The error which I am getting:

Undefined index: project_id

Could someone help me out?

Upvotes: 0

Views: 59

Answers (2)

baikho
baikho

Reputation: 5368

Try this (note the [0]):

$project_id = $json[0]["project_id"];

Upvotes: 1

Fky
Fky

Reputation: 2173

Missing one level

$str = file_get_contents($tmp);
$json = json_decode($str, true);
foreach($json as $j){
 echo $j['project_id'];
}

Your response datas is an Array of jsons object so have to loop on it.

Also, if you want bypass loop and get directly first result you can do this :

$str = file_get_contents($tmp);    
$json = current(json_decode($str, true));
$project_id = $json["project_id"];

Upvotes: 0

Related Questions