php 使用 Laravel 读取文件内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26730861/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:01:38  来源:igfitidea点击:

Read file contents with Laravel

phplaravel

提问by Cheskq

I am trying to read the contents of a file line by line with Laravel. However, I can't seem to find anything about it anywhere.

我正在尝试使用 Laravel 逐行读取文件的内容。但是,我似乎无法在任何地方找到有关它的任何信息。

Should I use the fopen function or can I do it with the File::get() function?

我应该使用 fopen 函数还是可以使用 File::get() 函数?

I've checked the API but there doesn't seem to have a function to read the contents of the file.

我已经检查了 API,但似乎没有读取文件内容的功能。

回答by KyleK

You can use simple PHP:

您可以使用简单的 PHP:

foreach(file('yourfile.txt') as $line) {
    // loop with $line for each line of yourfile.txt
}

回答by Victor Axelsson

You can use the following to get the contents:

您可以使用以下内容来获取内容:

$content = File::get($filename);

Which will return a Illuminate\Filesystem\FileNotFoundExceptionif it's not found. If you want to fetch something remote you can use:

Illuminate\Filesystem\FileNotFoundException如果找不到,它将返回一个。如果你想获取远程的东西,你可以使用:

$content = File::getRemote($url);

Which will return falseif not found.

false如果找不到,它将返回。

When you have the file you don't need laravel specific methods for handling the data. Now you need to work with the content in php. If you wan't to read the lines you can do it like @kylek described:

当您拥有该文件时,您不需要 laravel 特定的方法来处理数据。现在您需要处理 php 中的内容。如果你不想阅读这些行,你可以像@kylek 描述的那样做:

 foreach($content as $line) {
    //use $line 
}

回答by toni rmc

You can use

您可以使用

try
{
    $contents = File::get($filename);
}
catch (Illuminate\Contracts\Filesystem\FileNotFoundException $exception)
{
    die("The file doesn't exist");
}