Paco
Paco

Reputation: 129

Decode json data from .json file in php

I am trying to output some json data from a json file via php but it does not seem to work. I tried this:

<?php
    $jsonFile = file_get_contents('dataset/dataset.json');
    $data = json_decode($jsonFile, true);

    echo $data->{'data'}[0]->{'letter'}
?>

The json file is following:

{
    "data":[
        {
            "letter":"A",
            "blocks":{
                "1":"0",
                "2":"0",
                "3":"0",
                "4":"0",
                "5":"0"
            }
        }
]}

Basically it should output the letter "A" but it outputs nothing. What did I do wrong? Thanks

P.S. I tried to do it like here: How to process JSON in PHP? but it does not work.

Upvotes: 0

Views: 264

Answers (2)

Christian Gollhardt
Christian Gollhardt

Reputation: 17034

This says, you get an array (the true parameter):

$data = json_decode($jsonFile, true);

You can see this if you do this:

print_r($data);

Try this:

echo $data['data'][0]['letter'];

Upvotes: 1

MH2K9
MH2K9

Reputation: 12039

After json_decode($jsonFile, true) your data is in array. So you should not access using object. Access data by array index. Try this..

echo $data['data'][0]['letter'];

More about json_decode()

Upvotes: 2

Related Questions