-2

Hi this question has similarity with this post:

But unfortunately, it's not working with PHP.

header('charset=utf8');
 $rr=file_get_contents("https://www.google.com/finance/info?q=NSE:TCS");
 $json = json_decode($rr, true); 
  echo '<pre>' . print_r($json, true) . '</pre>';

This shows only blank. No data.

using only file_get_contents gives something like this.

// [ { "id": "784961" ,"t" : "TCS" ,"e" : "NSE" ,"l" : "2,437.00" ,"l_fix" : 
 "2437.00" ,"l_cur" : "₹2,437.00" ,"s": "0" ,"ltt":"3:49PM GMT+5:30" ,"lt" : 
 "Jul 20, 3:49PM GMT+5:30" ,"lt_dts" : "2017-07-20T15:49:12Z" ,"c" : "-12.60" 
  ,"c_fix" : "-12.60" ,"cp" : "-0.51" ,"cp_fix" : "-0.51" ,"ccol" : "chr" 
  ,"pcls_fix" : "2449.6" } ]

If json_decode doesn't work then what are my options to do it in other way. I will show data in table format or each shares.

full quote link
http://www.google.com/finance/info?infotype=infoquoteall&q=NSE:TCS"
mimi
  • 335
  • 5
  • 25

1 Answers1

1

I did not understand the problem correctly at first. Basically, Google returns invalid JSON, that need to be "fixed" before using it:

$rr = trim(str_replace(array("\r", "\n", "//"), '', $rr));
$json = json_decode($rr);

Result:

array(1) { [0]=> object(stdClass)#1 (16) { ["id"]=> string(6) "784961" ["t"]=> string(3) "TCS" ["e"]=> string(3) "NSE" ["l"]=> string(8) "2,437.00" ["l_fix"]=> string(7) "2437.00" ["l_cur"]=> string(15) "₹2,437.00" ["s"]=> string(1) "0" ["ltt"]=> string(15) "3:49PM GMT+5:30" ["lt"]=> string(23) "Jul 20, 3:49PM GMT+5:30" ["lt_dts"]=> string(20) "2017-07-20T15:49:12Z" ["c"]=> string(6) "-12.60" ["c_fix"]=> string(6) "-12.60" ["cp"]=> string(5) "-0.51" ["cp_fix"]=> string(5) "-0.51" ["ccol"]=> string(3) "chr" ["pcls_fix"]=> string(6) "2449.6" } }
Gino Pane
  • 4,740
  • 5
  • 31
  • 46
  • I was having same thought with the "//" style :). how to access individual field? for example, stock quotes "l" – mimi Jul 20 '17 at 13:33
  • I tried doing it echo $arr[0]->l; I get error Undefined variable: arr, Trying to get property of non-object 2 errors. – mimi Jul 20 '17 at 13:59
  • 1
    @mimi for the exampke above it should be `$json[0]->l` – Gino Pane Jul 20 '17 at 15:32