user2811002
user2811002

Reputation: 55

Get values from json string

I am extracting the values from JSON but keep getting an empty result when I echo the value

$json='[[{"transTime":"2013-10-23 17:30:42","Forename":"Ian","Surname":"Graham","Address Line 1":"RG412GX"}]]';

$obj2 = json_decode($json, true);

$displayName = $obj2->Surname;

echo"$displayName";

Upvotes: 0

Views: 103

Answers (4)

TheWolf
TheWolf

Reputation: 1385

There are several issues with the code you provided. First, your json text is stored in $json, but you try to decode $xmlresponse. I guess that's just a copy/paste error, though. Second, you try to access the surname using the object syntax although you explicitly force json_decode to decode objects as associative arrays. Third, the json provided encodes an object in an array in an array. You ignore the nested structure of the response.

Try this:

$json='[[{"transTime":"2013-10-23 17:30:42","Forename":"Ian","Surname":"Graham","Address Line 1":"RG412GX"}]]';
$response = json_decode($json);
$displayName = $response[0][0]->Surname;

echo $displayName;

Upvotes: 0

Gavin
Gavin

Reputation: 2153

This should be something like:

$json='[[{"transTime":"2013-10-23 17:30:42","Forename":"Ian","Surname":"Graham","Address    Line 1":"RG412GX"}]]';

$obj2 = json_decode($json, true);

$displayName = $obj2->Surname;

echo"$displayName";

You are mixing up / making up variable names...

Upvotes: 0

peiman F.
peiman F.

Reputation: 1658

you have one object in other one in this json string

$json='[[{"transTime":"2013-10-23 17:30:42","Forename":"Ian","Surname":"Graham","Address Line 1":"RG412GX"}]]';

$obj2 = json_decode($json);

print_r($obj2);

Upvotes: 1

Francesco Marasco
Francesco Marasco

Reputation: 1

Try this:

<?php
$json='[[{"transTime":"2013-10-23 17:30:42","Forename":"Ian","Surname":"Graham","Address Line 1":"RG412GX"}]]';
$obj2 = json_decode($json, true);
$displayName = $obj2[0][0]['Surname'];
echo "$displayName";
?>

Upvotes: 0

Related Questions