简体   繁体   English

如何使用 Laravel 读取目录中的所有文件内容

[英]how to read all file contents in a directory with Laravel

I have so many files in a directory and I want to read all of them and save them in Database.我在一个目录中有很多文件,我想读取所有文件并将它们保存在数据库中。 I know how to do it but the way i know is that all file contents will load to the memory at the same time and web application will be dead.我知道该怎么做,但我知道的方式是所有文件内容将同时加载到 memory 和 web 应用程序将死。 I tend to put some limits like it reads 300 files at the same time and after that it goes through the next 300 files.我倾向于设置一些限制,例如它同时读取 300 个文件,然后再读取接下来的 300 个文件。 as you can see I have 736 files here.如您所见,我在这里有 736 个文件。

在此处输入图像描述

this is my sample file contents:这是我的示例文件内容: 在此处输入图像描述

I'm using this code to split them.我正在使用此代码来拆分它们。

    foreach ($contents as $content) {
        $slice = preg_split("/\\r\\n|\\r|\\n/", $content);
    }

and results:和结果: 在此处输入图像描述

You can use laravel's filesytem and the Storage facade to achieve this:你可以使用laravel的文件系统和 Storage 门面来实现:

$files = Storage::disk('public')->files('path/to/files');

foreach ($files as $file) {
    $contents = Storage::disk('public')->get($file);
    // Save contents to DB;
}

You could also do them in batches by building up an array of contents您也可以通过构建内容数组来分批执行它们

$files = Storage::disk('public')->files('path/to/files');
$contents = [];
$toMove = [];

foreach ($files as $file) {
    $content = Storage::disk('public')->get($file);
    $slice = preg_split("/\\r\\n|\\r|\\n/", $content);
    
    $contents[] = [
         'metadata' => $slice[0],
         'data1' => $slice[1],
         'data2' => $slice[2],
         'data3' => $slice[3],
    ];
    
    $toMove[] = $file;

    if (count($contents) === 10) {
        DB::table('informations')->insert($contents);

        foreach($toMove as $file) {
            Storage::disk('public')
                ->move($file , 'done/'.Str::of($file)->after('/')); 
        }

        $contents = [];
        $toMove = [];
    }
}

if (count($contents)) {
    DB::table('informations')->insert($contents);

    foreach($toMove as $file) {
        Storage::disk('public')
            ->move($file , 'done/'.Str::of($file)->after('/')); 
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM