# CakePHP 4 Export To CSV

> This tutorial will show how to export a list of records to .csv file format in CakePHP 4. This function is useful if you want to extract the record into .csv format which can be open using Microsoft Excel. The CakePHP-csv view plugin will be used to generate the .csv file.

- URL: https://www.codethepixel.com/cakephp-4-export-to-csv
- Author: Asyraf Wahi Anuar (https://www.codethepixel.com/author/asyraf-wahi-anuar)
- Published: 2020-05-29
- Updated: 2021-11-08
- Category: CakePHP
- Tested with: CakePHP 4.x
- Tags: CakePHP, CSV, Export
- Reading time: 3 min

This tutorial will show how to export a list of records to .csv file format in CakePHP 4. This function is useful if you want to extract the record into .csv format which can be open using Microsoft Excel. The [CakePHP-csvview](https://github.com/FriendsOfCake/cakephp-csvview) plugin will be used to generate the .csv file.

Download the plugin from the Github repository using composer:

```bash
$ composer require friendsofcake/cakephp-csvview
```

Load the plugin using the console:

```bash
$ bin/cake plugin load CsvView
```

or manually load the plugin using the following code in ...\\src\\Application.php:

`src/Application.php`

```php
public function bootstrap(): void
{
    $this->addPlugin('CsvView');
```

Let assume that the list to be exported is a user table. You need to create a new public function to process the request as shown below (it will export all columns and download with file name user.csv):

`src/Controller/UsersController.php`

```php
public function csv()
{
    $this->response = $this->response->withDownload('user.csv');
    $users = $this->Users->find();
    $_serialize = 'users';

    $this->viewBuilder()->setClassName('CsvView.Csv');
    $this->set(compact('users', '_serialize'));
}
```

Or if you want to add a header to your .csv file, add $\_header and $\_extract as shown below:

```php
public function csv()
{
    $this->response = $this->response->withDownload('user.csv');
    $users = $this->Users->find();
    $_serialize = 'users';
    $_header = ['ID', 'Name', 'Username', 'Role', 'Created', 'Modified'];
    $_extract = ['id', 'name', 'username', 'role', 'created', 'modified'];

    $this->viewBuilder()->setClassName('CsvView.Csv');
    $this->set(compact('users', '_serialize', '_header', '_extract'));
}
```

In your index file, create a link/button to download the .csv file:

```php
<?= $this->Html->link('Download CSV', ['action' => 'csv']) ?>
```

That all. Happy coding :)
