Laravel 5.6 如何逐行读取文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53008105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5.6 how to read text file line by line
提问by mr.boris
Without Laravel I can use simple code to read text file by line:
如果没有 Laravel,我可以使用简单的代码逐行读取文本文件:
$file = fopen("whatever/file.txt", "r") or exit("Unable to open file!");
while(!feof($file)) {
echo fgets($file). "<br>";
}
fclose($file);
With Laravel this simple thing becomes overwhelming due to local file storage location.
对于 Laravel,由于本地文件存储位置,这个简单的事情变得势不可挡。
I.e. I can get file contents with Storage::get('whatever/file.txt')
method, but how to get just a file and then read it in a loop?
即我可以使用Storage::get('whatever/file.txt')
方法获取文件内容,但是如何仅获取文件然后循环读取它?
I've tried to use File::get('whatever/file.txt')
method but get an error: File does not exist at path
.
我尝试使用File::get('whatever/file.txt')
方法但得到一个错误:File does not exist at path
。
How to read file from local storage (not public) line by line with Laravel?
如何使用 Laravel 从本地存储(非公共)逐行读取文件?
回答by Sasa Blagojevic
You can get your file like this:
您可以像这样获取文件:
$file = fopen(storage_path("whatever/file.txt"), "r");
This will result in a path similar to this
'/var/www/storage/whatever/file.txt'
or '/var/www/foo/storage/whatever/file.txt'
if you are serving multiple websites from the same server, it will depend on your setup, but you get the gist of it. Then you can read your file;
这将产生与此类似的路径,
'/var/www/storage/whatever/file.txt'
或者'/var/www/foo/storage/whatever/file.txt'
如果您从同一服务器为多个网站提供服务,这将取决于您的设置,但您已了解其要点。然后你就可以读取你的文件了;
while(!feof($file)) {
echo fgets($file). "<br>";
}
fclose($file);
回答by Problem Solver
You need to know where your file lives. You also need a path to get there. E.g., if your file is located in the storage folder, you could do
您需要知道您的文件所在的位置。您还需要一条通往那里的道路。例如,如果您的文件位于存储文件夹中,您可以这样做
File::get(storage_path('whatever/test.txt'));
dd($contents);
回答by Prashant Deshmukh.....
Hope it will help
希望它会有所帮助
File::get(storage_path('whatever/file.txt'));
回答by mr.boris
So confusing!
好纠结!
My file was in the folder storage/app/whatever/file.txt
but Laravel storage("whatever/file.txt")
method recognizes it as storage/whatever/file.txt
path.
我的文件在文件夹中,storage/app/whatever/file.txt
但 Laravelstorage("whatever/file.txt")
方法将其识别为storage/whatever/file.txt
路径。
As I said before it is overwhelming and confusing a lot.
正如我之前所说,它是压倒性的,而且很混乱。
So, fopen('storage/app/whatever/file.txt')
works for me.
所以,fopen('storage/app/whatever/file.txt')
对我有用。