laravel 读取文件
时间: 2023-06-21 10:13:24 浏览: 57
在 Laravel 中读取文件可以使用 PHP 的内置函数 `file_get_contents()` 或者 Laravel 提供的 `Storage` Facade。
如果使用 `file_get_contents()`,可以直接传入文件路径,如下:
```php
$fileContents = file_get_contents('/path/to/file');
```
如果使用 `Storage` Facade,需要先通过 `disk()` 方法指定磁盘,然后使用 `get()` 方法获取文件内容,如下:
```php
use Illuminate\Support\Facades\Storage;
$fileContents = Storage::disk('local')->get('file.txt');
```
其中,`local` 是默认的磁盘名称,可以在 `config/filesystems.php` 文件中进行配置。`get()` 方法可以接收文件路径或者 `Illuminate\Contracts\Filesystem\File` 实例作为参数。
如果需要按行读取文件内容,可以使用 `file()` 函数或者 `Storage` Facade 的 `readLines()` 方法,如下:
```php
// 使用 file() 函数
$lines = file('/path/to/file', FILE_IGNORE_NEW_LINES);
// 使用 Storage Facade
use Illuminate\Support\Facades\Storage;
$lines = Storage::disk('local')->readLines('file.txt');
```
以上代码会将每一行作为数组中的一个元素返回。`readLines()` 方法也可以接收可选的第二个参数来指定行结束符,例如:
```php
$lines = Storage::disk('local')->readLines('file.txt', "\r\n");
```
这里的 `\r\n` 是 Windows 下的行结束符,在 Linux 下可以使用 `\n`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![.zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![.zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)