流明从文件中读取 JSON
Lumen read JSON from file
我正在使用 Lumen Framework
并试图从 json
文件中为我的数据库做种。我正在做这样的事情:
public function run()
{
$json = json_decode(file_get_contents('database/seed/file.json'), true);
...
}
但是当我执行种子命令 php artisan db:seed
时,我得到这个错误:
[ErrorException]
file_get_contents(database/seed/file.json): failed to open stream: No such file or directory
我尝试这样做: 我得到了这个:
[Symfony\Component\Debug\Exception\FatalThrowableError]
Call to undefined function public_path()
知道我做错了什么吗?
谢谢
使用__DIR__
找出脚本路径
public function run()
{
dd(__DIR__);
}
对于这个例子,假设输出是 /home/vagrant/Code/app/Http/Controllers
。
现在这应该可以工作了(如果文件权限正确)
public function run()
{
$file_path = realpath(__DIR__ . '/../../database/seed/file.json');
$json = json_decode(file_get_contents($file_path), true);
// ...
}
我正在使用 Lumen Framework
并试图从 json
文件中为我的数据库做种。我正在做这样的事情:
public function run()
{
$json = json_decode(file_get_contents('database/seed/file.json'), true);
...
}
但是当我执行种子命令 php artisan db:seed
时,我得到这个错误:
[ErrorException]
file_get_contents(database/seed/file.json): failed to open stream: No such file or directory
我尝试这样做:
[Symfony\Component\Debug\Exception\FatalThrowableError]
Call to undefined function public_path()
知道我做错了什么吗?
谢谢
使用__DIR__
找出脚本路径
public function run()
{
dd(__DIR__);
}
对于这个例子,假设输出是 /home/vagrant/Code/app/Http/Controllers
。
现在这应该可以工作了(如果文件权限正确)
public function run()
{
$file_path = realpath(__DIR__ . '/../../database/seed/file.json');
$json = json_decode(file_get_contents($file_path), true);
// ...
}