-1

This is the JSON file:

// [ { "id": "5417778" ,"t" : "TATAMTRDVR" ,"e" : "NSE" ,"l" : "329.80" ,"l_fix" : "329.80" ,"l_cur" : "Rs.329.80" ,"s": "0" ,"ltt":"11:11AM GMT+5:30" ,"lt" : "Jul 26, 11:11AM GMT+5:30" ,"lt_dts" : "2016-07-26T11:11:45Z" ,"c" : "-0.35" ,"c_fix" : "-0.35" ,"cp" : "-0.11" ,"cp_fix" : "-0.11" ,"ccol" : "chr" ,"pcls_fix" : "330.15" } ]

And my code is,

<?php
$json = file_get_contents('http://finance.google.com/finance/info?q=NSE:TATAMTRDVR');
$obj = json_decode($json);
echo $obj->id;
?>

The error message displayed is,

Notice: Trying to get property of non-object in C:\xampp\htdocs\fin\latest_stock.php on line 4

N3R4ZZuRR0
  • 2,400
  • 4
  • 18
  • 32

3 Answers3

2

It is not a valid json. Remove "// " from json response and your code will work fine.

Deepak
  • 104
  • 7
1

The object is contained within an array so you need to do this:

echo $obj[0]->id;

instead of

echo $obj->id;
halfer
  • 19,824
  • 17
  • 99
  • 186
Mubashar Abbas
  • 5,536
  • 4
  • 38
  • 49
0

First, convert it into a valid JSON. Remove the slashes ("//") first.

<?php
$response = file_get_contents('http://finance.google.com/finance/info?     q=NSE:TATAMTRDVR');
$modifiedResponse = str_replace('// ','',$response);
$obj = json_decode($modifiedResponse);
echo $obj[0]->id;
?>
N3R4ZZuRR0
  • 2,400
  • 4
  • 18
  • 32
Nikhil Mk
  • 151
  • 10