为什么我无法使用PHP获取JSON数据?

时间:2016-07-26 06:05:41

标签: php json

这是JSON文件:

  

// [{" id":" 5417778" " T" :" TATAMTRDVR" " E" :" NSE" " L" :   " 329.80" " l_fix" :" 329.80" " l_cur" :" Rs.329.80" ," s":" 0"   ," ltt":" 11:11 AM GMT + 5:30" " LT" :" 7月26日,11:11 AM 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" }]

我的代码是,

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

显示的错误信息是,

  

注意:尝试在第4行的C:\ xampp \ htdocs \ fin \ latest_stock.php中获取非对象的属性

3 个答案:

答案 0 :(得分:1)

该对象包含在一个数组中,因此您需要执行此操作:

echo $obj[0]->id;

而不是

echo $obj->id;

答案 1 :(得分:1)

这不是一个有效的json。从json响应中删除“//”,您的代码将正常工作。

答案 2 :(得分:0)

首先,将其转换为有效的JSON。首先删除斜杠(“//”)。

<?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;
?>