dqq3623 2017-05-01 19:14
浏览 145
已采纳

file_get_contents或从Controller读取JSON文件

I am getting started with the F3 Framework (Fat Free Framework) and so far it's great. Simple and light. I set it up so that my controllers are in a separate folder App/Controllers and that is working great using classes and namespaces. On thing I'm having trouble with is reading a JSON file from one of those controllers. My code is below:

$json = $f3->read('settings/templates.json');
$templates = json_decode($json);
var_dump($templates);
$fields = $templates->$template->fields;

I tried it like that and like this

$json = file_get_contents('settings/templates.json');
$templates = json_decode($json);
var_dump($templates);
$fields = $templates->$template->fields;

But either way I get a file not found error. So somehow, F3 is not finding the file. I'm not sure if I need to include this in the AUTOLOAD or if there is some better way to do this.

I tried it as a database like so and it finds the file, but somehow this doesn't seem right:

$db = new \DB\Jig ( 'settings/' , \DB\Jig::FORMAT_JSON );
$user= new \DB\Jig\Mapper($db, 'templates.json');
var_dump($templates);
$fields = $templates->$template->fields;

It seems like I shouldn't be using the DB class and Jig just to read a simple JSON file. Can someone please shed some light on this?

EDIT: Ok the answer below helped, but in my particular case, everything (the syntax) was right. I think the reason it didn't work was because I had the paths wrong in this line of my index.php

$f3->set('AUTOLOAD','App/Controllers/');
  • 写回答

1条回答 默认 最新

  • doucheng9304 2017-05-03 07:14
    关注

    The issue you're facing is not related to the framework but to your understanding of relatives paths in PHP. Relative paths are always relative to the working directory.

    If you're using the framework for the web (and not in CLI mode), the working directory is the directory where your index.php is located, as long as you don't explicitly change the working directory with the chdir command.

    You can verify it by echoing getcwd() at the very top of your script.

    That means that any relative path used in your application (no matter if it's being called from index.php, lib/web.php, app/controllers/foo.php or any file located in any directory) is relative to that directory.

    So in your case, the settings directory is expected to be found in the same directory as index.php:

    apps/
      controllers/
    settings/
      templates.json
    index.php
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?