2016-04-30 79 views
-1

我在如何从php的外部json文件读取时遇到一些问题。用php阅读表格.json

我试过这个解决方案:

$data = json_decode(file_get_contents('/data/usersdata.json'),TRUE); 
print_r ($data); 

在usersdata.json现在是:

{"name":"admin","password":"admin","permission":"admin"} 

我的问题是,我看不到任何东西在屏幕上,我希望把数据从我的json文件到一个$ data数组,或者可用的东西。

+0

使用'print_r($ data)'并检查它是否正确解码。 –

+2

假设'/ data/usersdata.json'存在,你的代码_应该工作。 –

+1

如果确实存在,请检查权限。如果你是从Web服务器运行它,用户试图访问它可能是'apache'或'nginx'什么的。 –

回答

1

测试在PHP 5.6(毫安)

我复制你的榜样,一切都会按预期

try { 
 
    $fileData = file_get_contents('src/data.json'); 
 
    $data = json_decode($fileData, true); 
 

 
    print_r($data); 
 
    
 
} catch(Exception $e) { 
 
    echo $e->getMessage(); 
 
}

输出:

Array ([name] => admin [password] => admin [permission] => admin)

  • 开始使用try/catch语句捕获任何非致命错误
  • 确保error_reporting is set to E_ALL
  • 在发展模式/阶段避免嵌套功能,因为它使调试困难和更可读。用几行代码在这里保存一行,不会影响你的性能。