0

I have the following JSON file that I need to extract a value and assign it to a PHP variable. The value I need is "icn".

{
  "apiVersion": "1.0",
  "data": {
    "updated": 20160331141332,
    "totalItems": 1,
    "currentItemCount": 1,
    "items": [
      {
        "birthDate": "20171101",
        "fullName": "DOE,JOHN D",
        "icn": "889081784V888383",
        "pid": "55R1;60004"
      }
    ]
  }
}

I have tried the following but get no results.

$myjson = file_get_contents('http://testurl.org/info.json');
print_r(json_decode($myjson->data->items[0]->icn,true));

echo "<br>LAST-Error:"; echo json_last_error(); 
echo "<br>LAST-Error-Msg:"; echo json_last_error_msg();

Results are

LAST-Error:0
LAST-Error-Msg:No error
user2704404
  • 149
  • 1
  • 1
  • 8

2 Answers2

0

I figured out where I went wrong.

$myjson = file_get_contents('http://testurl.org/info.json');
$dec = (Array)json_decode($myjson,true);
$ICN = $dec["data"]["items"][0]["icn"];
user2704404
  • 149
  • 1
  • 1
  • 8
0

$myjson is a string, you treat it as object:

$myjson->data->items[0]->icn

You have to first decode JSON string, then you can retrieve JSON elements.

Simply move closing parenthesis and remove True option:

print_r( json_decode( $myjson->data->items[0]->icn, true ) );
#                             ┌──────────────────────────┘
print_r( json_decode( $myjson )->data->items[0]->icn );
fusion3k
  • 11,568
  • 4
  • 25
  • 47