Arif
Arif

Reputation: 1211

Fetch json data using PHP

I have a json file and I want to display it data using PHP. My below code gives me error,

$json = file_get_contents('data.json'); 
$data = json_decode($json,true);
$users = $data['devices'];
foreach($users as $user)
{
echo $user['id'];
echo $user['user'];
}

When I replace the 3rd LOC with $users = $data['user']; then it display some data with single alphabet i don't know in which order.

Data.json file contains the following data

{
"user":
    {
    "id":"#03B7F72C1A522631",
    "user":"[email protected]",
    "password":"123",
    "email":"[email protected]",
    "name":"m",
    "creationDate":1385048478,
    "compression":true,
    "imageProfile":"medium",
    "videoProfile":"medium",
    "blockAdvert":true,
    "blockTracking":true,
    "devices":[
        {
        "id":"#13C73379A7CC2310",
        "udid":"cGMtd2luNi4xLV",
        "user":"[email protected]",
        "creationDate":1385048478,
        "status":"active",
        }, 
        {
        "id":"#FE729556EDD9910D",
        "udid":"C1N1",
        "user":"[email protected]",
        "creationDate":1385291938,
        "status":"active",
        }]
    },
"status":
    {
    "version":"0.9.5.0",
    "command":"getuser",
    "opf":"json",
    "error":false,
    "code":0
    }
}

Upvotes: 1

Views: 5493

Answers (4)

ddelnano
ddelnano

Reputation: 469

You are not accessing your json correctly. You need to access it like this.

$yourVariable = $data['users']['devices'];

Try that.

Upvotes: 1

srain
srain

Reputation: 9082

I think you may want do display all the devices info, you can change you code to:

$json = file_get_contents('data.json'); 
$data = json_decode($json,true);

// change the variable name to devices which is clearer.
$devices = $data['user']['devices'];
foreach ($devices as $device)
{
    echo $device['id'];
    echo $device['user'];
}

Upvotes: 3

l-x
l-x

Reputation: 1571

This should work;

$json = file_get_contents('data.json'); 
$data = json_decode($json,true);
$users = $data['user']['devices'];
foreach($users as $user) {
    echo $user['id'];
    echo $user['user'];
}

There is one key before 'devices'.

Upvotes: 4

G.Mendes
G.Mendes

Reputation: 1201

I believe you skipped 1 node, try:

$users = $data['user']['devices'];

Upvotes: 4

Related Questions