A thinkphp package that can easily generate CSV files from Eloquent models.

Keywords: PHP ElasticSearch search engine

composer require whereof/think-csv

$users = User::select(); // All users
$csvExporter = new \whereof\think\csv\Export();
$csvExporter->build($users, ['email', 'name'])->download();

Create CSV

$exporter - > build ($modelcollection, $fields) requires three parameters. The first is the model (a collection of models), the second is the name of the field to be exported, and the third is the configuration, which is optional.

$csvExporter->build(User::select(), ['email', 'name', 'created_at']);

output option

download

To download a file to a browser:

$csvExporter->download();

If you wish, you can provide the file name:

$csvExporter->download('active_users.csv');

If no file name is given, a file name with a date and time is generated.

Advanced output

Laracvs use League CSV . You can do what League CSV can do. You can obtain the underlying League CSV writer and reader instances by calling:

$csvWriter = $csvExporter->getWriter();
$csvReader = $csvExporter->getReader();

Then you can do several things, such as:

$csvString = $csvWriter->getContent(); // To get the CSV as string
$csvReader->jsonSerialize(); // To turn the CSV in to an array

For more information, see League CSV document.

Custom title

The above code example will generate an email with a title, name, and created_ CSV of at and the corresponding line after.

If you want to change the title with a custom label, just pass it as an array value:

$csvExporter->build(User::select(), ['email', 'name' => 'Full Name', 'created_at' => 'Joined']);

Now the name column will display the title, Full Name, but it will still get the value from the field of the name model.

Untitled

You can also cancel the CSV header:

$csvExporter->build(User::select(), ['email', 'name', 'created_at'], [
    'header' => false,
]);

Modify or add values

A hook is triggered before processing a database row. For example, if you want to change the date format, you can do so.

$csvExporter = new \Laracsv\Export();
$users = User::get();

// Register the hook before building
$csvExporter->beforeEach(function ($user) {
    $user->created_at = date('f', strtotime($user->created_at));
});

$csvExporter->build($users, ['email', 'name' => 'Full Name', 'created_at' => 'Joined']);

**Note: * * if the beforeEach callback returns false, the whole line will be excluded from CSV. It's convenient to filter some guilds.

Add fields and values

You can also add fields that do not exist in the database table and dynamically add values:

// The notes field doesn't exist so values for this field will be blank by default
$csvExporter->beforeEach(function ($user) {
    // Now notes field will have this value
    $user->notes = 'Add your notes';
});

$csvExporter->build($users, ['email', 'notes']);

Block construction

For larger datasets that may consume more memory, you can use the builder instance to process the results in blocks. Similar to row related hooks, block related hooks can be used in this case, such as eager loading or similar block based operations. The behavior between the two hooks is similar; It is called before each block and takes the entire collection as a parameter. If false returns, the entire block is skipped and the code continues to the next.

// Perform chunk related operations
$export->beforeEachChunk(function ($collection) {
   
});
$export->buildFromBuilder(User::newQuery(),['email', 'name']);
$export->buildFromBuilder(Db::table('user'),['email', 'name']);

The default block size is set to 1000 results, but you can change the block size to 500 by passing it to buildFromBuilder. Example in $config.

$export->buildFromBuilder(User::newQuery(),['email', 'name'], ['chunk' => 500]);

Posted by ckdoublenecks on Sat, 20 Nov 2021 18:43:41 -0800