PHPackages                             friendsofcake/cakephp-csvview - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Templating &amp; Views](/categories/templating)
4. /
5. friendsofcake/cakephp-csvview

ActiveCakephp-plugin[Templating &amp; Views](/categories/templating)

friendsofcake/cakephp-csvview
=============================

A CSV View class for CakePHP

5.1.0(1mo ago)1782.6M↓23.5%65[1 issues](https://github.com/FriendsOfCake/cakephp-csvview/issues)[1 PRs](https://github.com/FriendsOfCake/cakephp-csvview/pulls)4MITPHPCI passing

Since Sep 20Pushed 1mo ago12 watchersCompare

[ Source](https://github.com/FriendsOfCake/cakephp-csvview)[ Packagist](https://packagist.org/packages/friendsofcake/cakephp-csvview)[ Docs](https://github.com/friendsofcake/cakephp-csvview)[ RSS](/packages/friendsofcake-cakephp-csvview/feed)WikiDiscussions 5.x Synced yesterday

READMEChangelog (10)Dependencies (6)Versions (33)Used By (4)

[![CI](https://github.com/FriendsOfCake/cakephp-csvview/actions/workflows/ci.yml/badge.svg)](https://github.com/FriendsOfCake/cakephp-csvview/actions/workflows/ci.yml)[![Coverage Status](https://camo.githubusercontent.com/b1d546543d28417692b09d878dcd4951a1a9bd4bfe1df5ccab3adb1afff94f37/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f467269656e64734f6643616b652f63616b657068702d637376766965772e7376673f7374796c653d666c61742d737175617265)](https://codecov.io/gh/FriendsOfCake/cakephp-csvview)[![Total Downloads](https://camo.githubusercontent.com/6be7f93d9687e5e666dcb0ecdec53c5002f94b4898a5bf12bc89c1666cecda10/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f667269656e64736f6663616b652f63616b657068702d637376766965772e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/friendsofcake/cakephp-csvview)[![Latest Stable Version](https://camo.githubusercontent.com/7daad25c1191a7876aadc8824a39824c679eaea52e683de56ce1c88966f1075d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f667269656e64736f6663616b652f63616b657068702d637376766965772e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/friendsofcake/cakephp-csvview)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.txt)

CsvView Plugin
==============

[](#csvview-plugin)

Quickly enable CSV output of your model data.

This branch is for CakePHP **5.x**. For details see [version map](https://github.com/FriendsOfCake/cakephp-csvview/wiki#cakephp-version-map).

Background
----------

[](#background)

I needed to quickly export CSVs of stuff in the database. Using a view class to iterate manually would be a chore to replicate for each export method, so I figured it would be much easier to do this with a custom view class, like JsonView or XmlView.

Installation
------------

[](#installation)

```
composer require friendsofcake/cakephp-csvview

```

### Enable plugin

[](#enable-plugin)

Load the plugin by running command

```
bin/cake plugin load CsvView

```

Usage
-----

[](#usage)

To export a flat array as a CSV, one could write the following code:

```
public function export()
{
    $data = [
        ['a', 'b', 'c'],
        [1, 2, 3],
        ['you', 'and', 'me'],
    ];

    $this->set(compact('data'));
    $this->viewBuilder()
        ->setClassName('CsvView.Csv')
        ->setOption('serialize', 'data');
}
```

All variables that are to be included in the csv must be specified in the `serialize` view option, exactly how `JsonView` or `XmlView` work.

It is possible to have multiple variables in the csv output:

```
public function export()
{
    $data = [['a', 'b', 'c']];
    $data_two = [[1, 2, 3]];
    $data_three = [['you', 'and', 'me']];

    $serialize = ['data', 'data_two', 'data_three'];

    $this->set(compact('data', 'data_two', 'data_three'));
    $this->viewBuilder()
        ->setClassName('CsvView.Csv')
        ->setOption('serialize', $serialize);
}
```

If you want headers or footers in your CSV output, you can specify either a `header` or `footer` view option. Both are completely optional:

```
public function export()
{
    $data = [
        ['a', 'b', 'c'],
        [1, 2, 3],
        ['you', 'and', 'me'],
    ];

    $header = ['Column 1', 'Column 2', 'Column 3'];
    $footer = ['Totals', '400', '$3000'];

    $this->set(compact('data'));
    $this->viewBuilder()
        ->setClassName('CsvView.Csv')
        ->setOptions([
            'serialize' => 'data',
            'header' => $header,
            'footer' => $footer,
        ]);
}
```

You can also specify the delimiter, end of line, newline, escape characters and byte order mark (BOM) sequence using `delimiter`, `eol`, `newline`, `enclosure`and `bom` respectively:

```
public function export()
{
    $data = [
        ['a', 'b', 'c'],
        [1, 2, 3],
        ['you', 'and', 'me'],
    ];

    $this->set(compact('data'));
    $this->viewBuilder()
        ->setClassName('CsvView.Csv')
        ->setOptions([
            'serialize' => 'data',
            'delimiter' => chr(9),
            'enclosure' => '"',
            'newline' => '\r\n',
            'eol' => '~',
            'bom' => true,
        ]);
}
```

The defaults for these options are:

- `delimiter`: `,`
- `enclosure`: `"`
- `newline`: `\n`
- `eol`: `\n`
- `bom`: false
- `setSeparator`: false

The `eol` option is the one used to generate newlines in the output. `newline`, however, is the character that should replace the newline characters in the actual data. It is recommended to use the string representation of the newline character to avoid rendering invalid output.

Some reader software incorrectly renders UTF-8 encoded files which do not contain byte order mark (BOM) byte sequence. The `bom` option is the one used to add byte order mark (BOM) byte sequence beginning of the generated CSV output stream. See [`Wikipedia article about byte order mark`](http://en.wikipedia.org/wiki/Byte_order_mark)for more information.

The `setSeparator` option can be used to set the separator explicitly in the first line of the CSV. Some readers need this in order to display the CSV correctly.

If you have complex model data, you can use the `extract` view option to specify the individual [`Hash::extract()`-compatible](http://book.cakephp.org/4/en/core-libraries/hash.html) paths or a callable for each record:

```
public function export()
{
    $posts = $this->Posts->find();
    $header = ['Post ID', 'Title', 'Created'];
    $extract = [
        'id',
        function (array $row) {
            return $row['title'];
        },
        'created'
    ];

    $this->set(compact('posts'));
    $this->viewBuilder()
        ->setClassName('CsvView.Csv')
        ->setOptions([
            'serialize' => 'posts',
            'header' => $header,
            'extract' => $extract,
        ]);
}
```

If your model data contains some null values or missing keys, you can use the `null` option, just like you'd use `delimiter`, `eol`, and `enclosure`, to set how null values should be displayed in the CSV.

`null` defaults to `''`.

Extract paths now consistently resolve through `Hash::get()`, so missing keys become `null`. If an extract path resolves to an array or object that cannot be stringified, use a callable extractor to flatten it before rendering.

#### Automatic view class switching

[](#automatic-view-class-switching)

You can use the controller's content negotiation feature to automatically have the CsvView class switched in as follows.

Enable `csv` extension parsing using `$routes->addExtensions(['csv'])` within required scope in your app's `routes.php`.

```
// PostsController.php

// Add the CsvView class for content type negotiation
public function initialize(): void
{
    parent::initialize();

    $this->addViewClasses(['csv' => 'CsvView.Csv']);
}

// Controller action
public function index()
{
    $posts = $this->Posts->find();
    $this->set(compact('posts'));

    if ($this->request->is('csv')) {
        $serialize = 'posts';
        $header = array('Post ID', 'Title', 'Created');
        $extract = array('id', 'title', 'created');

        $this->viewBuilder()->setOptions(compact('serialize', 'header', 'extract'));
    }
}
```

With the above controller you can now access `/posts.csv` or use `Accept` header `text/csv` to get the data as csv and use `/posts` to get normal HTML page.

For really complex CSVs, you can also use your own view files. To do so, either leave `serialize` unspecified or set it to null. The view files will be located in the `csv` subdirectory of your current controller:

```
// View used will be in templates/Posts/csv/export.php
public function export()
{
    $posts = $this->Posts->find();
    $this->set(compact('posts'));
    $this->viewBuilder()
        ->setClassName('CsvView.Csv')
        ->setOption('serialize', null);
}
```

#### Setting a different encoding to the file

[](#setting-a-different-encoding-to-the-file)

If you need to have a different encoding in you csv file you have to set the encoding of your data you are passing to the view and also set the encoding you want for the csv file. This can be done by using `dataEncoding` and `csvEncoding`:

The defaults are:

- `dataEncoding`: `UTF-8`
- `csvEncoding`: `UTF-8`

\*\* Only if those two variable are different your data will be converted to another encoding.

CsvView uses the `iconv` extension by default to encode your data. You can change the php extension used to encode your data by setting the `transcodingExtension` option:

```
$this->viewBuilder()->setOption('transcodingExtension', 'mbstring');
```

The currently supported encoding extensions are as follows:

- `iconv`
- `mbstring`

#### Excel-friendly UTF-8 export

[](#excel-friendly-utf-8-export)

Microsoft Excel on Windows does not recognise a UTF-8 CSV unless it has a byte-order mark, CRLF line endings, and an explicit UTF-8 declaration. Setting all three options individually each time is repetitive and easy to get wrong.

The `excel` shorthand sets the right defaults in one go:

```
$this->viewBuilder()
    ->setClassName('CsvView.Csv')
    ->setOptions([
        'serialize' => 'data',
        'excel' => true,
    ]);
```

`excel => true` is equivalent to:

```
'bom' => true,
'eol' => "\r\n",
'csvEncoding' => 'UTF-8',
```

The shorthand always wins for the three keys it controls; if you need a different combination (e.g. UTF-16, no BOM) do not enable `excel` and set the individual keys yourself instead. Other CSV options (`delimiter`, `enclosure`, `setSeparator`, `header`, `extract`, etc.) are independent and behave normally.

#### Setting the downloaded file name

[](#setting-the-downloaded-file-name)

By default, the downloaded file will be named after the last segment of the URL used to generate it. Eg: `example.com/my-controller/my-action` would download `my-action.csv`, while `example.com/my-controller/my-action/first-param` would download `first-param.csv`.

> In IE you are required to set the filename, otherwise it will download as a text file.

To set a custom file name, use the `Response::withDownload()` method. The following snippet can be used to change the downloaded file from `export.csv` to `my-file.csv`:

```
public function export()
{
    $data = [
        ['a', 'b', 'c'],
        [1, 2, 3],
        ['you', 'and', 'me'],
    ];

    $this->setResponse($this->getResponse()->withDownload('my-file.csv'));
    $this->set(compact('data'));
    $this->viewBuilder()
        ->setClassName('CsvView.Csv')
        ->setOption('serialize', 'data');
}
```

#### Using a specific View Builder

[](#using-a-specific-view-builder)

In some cases, it is better not to use the current controller's View Builder `$this->viewBuilder()` as any call to `$this->render()` will compromise any subsequent rendering.

For example, in the course of your current controller's action, if you need to render some data as CSV in order to simply save it into a file on the server.

Do not forget to add to your controller:

```
use Cake\View\ViewBuilder;
```

So you can create a specific View Builder:

```
// Your data array
$data = [];

// Options
$serialize = 'data';
$delimiter = ',';
$enclosure = '"';
$newline = '\r\n';

// Create the builder
$builder = new ViewBuilder();
$builder
    ->setLayout(false)
    ->setClassName('CsvView.Csv')
    ->setOptions(compact('serialize', 'delimiter', 'enclosure', 'newline'));

// Then the view
$view = $builder->build($data);
$view->set(compact('data'));

// And Save the file
file_put_contents('/full/path/to/file.csv', $view->render());
```

###  Health Score

68

—

FairBetter than 99% of packages

Maintenance89

Actively maintained with recent releases

Popularity60

Solid adoption and visibility

Community37

Small or concentrated contributor base

Maturity74

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~171 days

Recently: every ~302 days

Total

28

Last Release

52d ago

Major Versions

2.3.0 → 3.0.02016-02-03

2.x-dev → 3.3.02018-08-15

3.4.0 → 4.0.0-beta2019-12-21

3.4.1 → 4.0.02020-08-06

4.x-dev → 5.0.02023-10-13

PHP version history (3 changes)2.0.0PHP &gt;=5.4.16

3.3.0PHP &gt;=5.6

4.1.0PHP &gt;=7.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/e31753bdd616948c7c8978ea9b5805378f75bfa62564e69c0aa2fd67aaf418c5?d=identicon)[ADmad](/maintainers/ADmad)

![](https://avatars.githubusercontent.com/u/5203126?v=4)[Friends Of Cake](/maintainers/FriendsOfCake)[@FriendsOfCake](https://github.com/FriendsOfCake)

---

Top Contributors

[![ADmad](https://avatars.githubusercontent.com/u/142658?v=4)](https://github.com/ADmad "ADmad (94 commits)")[![josegonzalez](https://avatars.githubusercontent.com/u/65675?v=4)](https://github.com/josegonzalez "josegonzalez (90 commits)")[![dereuromark](https://avatars.githubusercontent.com/u/39854?v=4)](https://github.com/dereuromark "dereuromark (48 commits)")[![joshuapaling](https://avatars.githubusercontent.com/u/145042?v=4)](https://github.com/joshuapaling "joshuapaling (10 commits)")[![skie](https://avatars.githubusercontent.com/u/130799?v=4)](https://github.com/skie "skie (10 commits)")[![Modicrumb](https://avatars.githubusercontent.com/u/3723383?v=4)](https://github.com/Modicrumb "Modicrumb (10 commits)")[![martonmiklos](https://avatars.githubusercontent.com/u/1609182?v=4)](https://github.com/martonmiklos "martonmiklos (9 commits)")[![gmponos](https://avatars.githubusercontent.com/u/5675248?v=4)](https://github.com/gmponos "gmponos (5 commits)")[![rrd108](https://avatars.githubusercontent.com/u/3147489?v=4)](https://github.com/rrd108 "rrd108 (4 commits)")[![ckeboss](https://avatars.githubusercontent.com/u/723809?v=4)](https://github.com/ckeboss "ckeboss (3 commits)")[![DIDoS](https://avatars.githubusercontent.com/u/5557268?v=4)](https://github.com/DIDoS "DIDoS (3 commits)")[![holywise](https://avatars.githubusercontent.com/u/13227871?v=4)](https://github.com/holywise "holywise (2 commits)")[![mozillamonks](https://avatars.githubusercontent.com/u/130826?v=4)](https://github.com/mozillamonks "mozillamonks (2 commits)")[![dakota](https://avatars.githubusercontent.com/u/83255?v=4)](https://github.com/dakota "dakota (2 commits)")[![tai-sho](https://avatars.githubusercontent.com/u/6727558?v=4)](https://github.com/tai-sho "tai-sho (1 commits)")[![ajibarra](https://avatars.githubusercontent.com/u/794722?v=4)](https://github.com/ajibarra "ajibarra (1 commits)")[![ashikkalavadiya](https://avatars.githubusercontent.com/u/5235607?v=4)](https://github.com/ashikkalavadiya "ashikkalavadiya (1 commits)")[![chronon](https://avatars.githubusercontent.com/u/57735?v=4)](https://github.com/chronon "chronon (1 commits)")[![daoutis](https://avatars.githubusercontent.com/u/27198161?v=4)](https://github.com/daoutis "daoutis (1 commits)")[![gaurish](https://avatars.githubusercontent.com/u/235844?v=4)](https://github.com/gaurish "gaurish (1 commits)")

---

Tags

cakephpcakephp-plugincsvphpexportcakephpcsvview

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/friendsofcake-cakephp-csvview/health.svg)

```
[![Health](https://phpackages.com/badges/friendsofcake-cakephp-csvview/health.svg)](https://phpackages.com/packages/friendsofcake-cakephp-csvview)
```

###  Alternatives

[cakephp/bake

Bake plugin for CakePHP

11212.0M202](/packages/cakephp-bake)[dereuromark/cakephp-queue

The Queue plugin for CakePHP provides deferred task execution.

308954.9k25](/packages/dereuromark-cakephp-queue)[dereuromark/cakephp-ide-helper

CakePHP IdeHelper Plugin to improve auto-completion

1882.3M44](/packages/dereuromark-cakephp-ide-helper)[dereuromark/cakephp-ajax

A CakePHP plugin that makes working with AJAX a piece of cake.

54262.9k1](/packages/dereuromark-cakephp-ajax)[anourvalar/office

Generate documents from existing Excel &amp; Word templates | Export tables to Excel (Grids)

24095.2k](/packages/anourvalar-office)[dereuromark/cakephp-tinyauth

A CakePHP plugin to handle user authentication and authorization the easy way.

131240.2k13](/packages/dereuromark-cakephp-tinyauth)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
