Skip to content
Advertisement

PHP load json data, output is empty

I try to load data from my JSON file into php see my code below

JSON:

{
    "drinks":[

    "1" {"coffee": "zwart", "country":"afrika"},
    
    "2" {"tea": "thee", "country":"china"},

    "3" {"water": "water", "country":"netherlands"},
    ]
}

PHP:

<?php
$str = file_get_contents('data.json');
$json = json_decode($str, true);
$drinks = $json['drinks'][0][coffee];

echo $drinks;
?>

If I run this code my output is empty. Who can help me in the right direction?

Advertisement

Answer

Your JSON input is NOT valid according to RFC 4627 (JSON specification). So the correct json string must be:

   {"drinks":[
              {"coffee": "zwart", "country":"afrika"},
              {"tea": "thee", "country":"china"},
              {"water": "water", "country":"netherlands"}
            ]
    }

so your code would work:

$str = file_get_contents('data.json');
$json = json_decode($str, true);    
$drinks = $json['drinks'][0]['coffee'];
echo $drinks;

Or at least, you must format your json string like below:

{
    "drinks":[    
      {
       "1": {"coffee": "zwart", "country":"afrika"},    
       "2": {"tea": "thee", "country":"china"},    
       "3": {"water": "water", "country":"netherlands"}
      }
   ]
}

And you can get your data in this way:

$str = file_get_contents('data.json');
$json = json_decode($str, true);
$drinks = $json['drinks'][0]['1']['coffee'];
echo $drinks;
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement