PHPackages                             kongka/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. kongka/cakephp-csvview

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

kongka/cakephp-csvview
======================

A CSV View class for CakePHP 3.x

3.2.3(7y ago)085MITPHPPHP &gt;=5.4.16

Since Sep 20Pushed 7y agoCompare

[ Source](https://github.com/kongka/cakephp-csvview)[ Packagist](https://packagist.org/packages/kongka/cakephp-csvview)[ Docs](http://github.com/friendsofcake/cakephp-csvview)[ RSS](/packages/kongka-cakephp-csvview/feed)WikiDiscussions master Synced 3d ago

READMEChangelog (1)Dependencies (1)Versions (17)Used By (0)

[![Build Status](https://camo.githubusercontent.com/b72e3c46e889f1dd4f5741209d1e3cde3cc09cbc63ad9c065eac25750ea18b41/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f467269656e64734f6643616b652f63616b657068702d637376766965772f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/FriendsOfCake/cakephp-csvview)[![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.

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.

Requirements
------------

[](#requirements)

- CakePHP 3.x
- PHP 5.4.16 or greater
- Patience

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

[](#installation)

*\[Using [Composer](http://getcomposer.org/)\]*

```
composer require kongka/cakephp-csvview:dev-master

```

### Enable plugin

[](#enable-plugin)

Load the plugin in your app's `config/bootstrap.php` file:

```
Plugin::load('CsvView', ['routes' => true]);

```

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'],
    ];
    $_serialize = 'data';

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

All variables that are to be included in the csv must be specified in the `$_serialize` view variable, 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->viewBuilder()->setClassName('CsvView.Csv');
    $this->set(compact('data', 'data_two', 'data_three', '_serialize'));
}
```

If you want headers or footers in your CSV output, you can specify either a `$_header` or `$_footer` view variable. Both are completely optional:

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

    $_serialize = 'data';
    $_header = ['Column 1', 'Column 2', 'Column 3'];
    $_footer = ['Totals', '400', '$3000'];

    $this->viewBuilder()->setClassName('CsvView.Csv');
    $this->set(compact('data', '_serialize', '_header', '_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'],
    ];

    $_serialize = 'data';
    $_delimiter = chr(9); //tab
    $_enclosure = '"';
    $_newline = '\r\n';
    $_eol = '~';
    $_bom = true;

    $this->viewBuilder()->setClassName('CsvView.Csv');
    $this->set(compact('data', '_serialize', '_delimiter', '_enclosure', '_newline', '_eol', '_bom'));
}
```

The defaults for these variables are:

- `_delimiter`: `,`
- `_enclosure`: `"`
- `_newline`: `\n`
- `_eol`: `\n`
- `_bom`: false
- `_setSeparator`: false

The `_eol` variable 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` variable 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` flag 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 variable to specify the individual [`Hash::extract()`-compatible](http://book.cakephp.org/3.0/en/core-libraries/hash.html) paths or a callable for each record:

```
public function export()
{
    $posts = $this->Post->find('all');
    $_serialize = 'posts';
    $_header = ['Post ID', 'Title', 'Created'];
    $_extract = [
        'id',
        function ($row) {
            return $row['title'];
        },
        'created'
    ];

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

If your model data contains some null values or missing keys, you can use the `$_null` variable, just like you'd use `$_delimiter`, `$_eol`, and `$_enclosure`, to set how null values should be displayed in the CSV.

`$_null` defaults to `''`.

You can use `Router::extensions()` and the `RequestHandlerComponent` to automatically have the CsvView class switched in as follows:

```
// In your routes.php file:
Router::extensions('csv');

// In your controller:
public $components = [
    'RequestHandler' => [
        'viewClassMap' => ['csv' => 'CsvView.Csv']
    ]
];

public function export()
{
    $posts = $this->Post->find('all');
    $this->set(compact('post'));

    if ($this->request->params['_ext'] === 'csv') {
        $_serialize = 'posts';
        $_header = array('Post ID', 'Title', 'Created');
        $_extract = array('id', 'title', 'created');

        $this->set(compact('_serialize', '_header', '_extract'));
    }
}
```

Access /posts/export.csv to get the data as csv and /posts/export to get normal page as usually.

For really complex CSVs, you can also simply 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 src/Template/Posts/csv/export.ctp
public function export()
{
    $posts = $this->Post->find('all');
    $_serialize = null;
    $this->viewBuilder()->setClassName('CsvView.Csv');
    $this->set(compact('posts', '_serialize'));
}
```

#### 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 `_extension` option:

```
$this->set('_extension', 'mbstring');
```

The currently supported encoding extensions are as follows:

- `iconv`
- `mbstring`

#### 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::download`](http://book.cakephp.org/3.0/en/controllers/request-response.html#sending-a-string-as-file) 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'],
    ];
    $_serialize = 'data';

    $this->response = $this->response->withDownload('my_file.csv'); // viewBuilder()->setClassName('CsvView.Csv');
    $this->set(compact('data', '_serialize'));
}
```

#### Using a specific View Builder

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

In some cases, it is better not to use the current model'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\View;
use Cake\View\ViewBuilder;
```

So you can create a specific View Builder:

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

// Params
$_serialize = 'data';
$_delimiter = ',';
$_enclosure = '"';
$_newline = '\r\n';

// Create the builder
$builder = new ViewBuilder;
$builder->layout = false;
$builder->setClassName('CsvView.Csv');

// Then the view
$view = $builder->build($data);
$view->set(compact('data', '_serialize', '_delimiter', '_enclosure', '_newline'));

// And Save the file
$file = new File('/full/path/to/file.csv', true, 0644);
$file->write($view->render());
```

License
-------

[](#license)

The MIT License (MIT)

Copyright (c) 2012 Jose Diaz-Gonzalez

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

###  Health Score

30

—

LowBetter than 62% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity9

Limited adoption so far

Community17

Small or concentrated contributor base

Maturity66

Established project with proven stability

 Bus Factor1

Top contributor holds 52.7% of commits — single point of failure

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 ~135 days

Recently: every ~181 days

Total

14

Last Release

2911d ago

Major Versions

1.3.0 → 2.0.02015-08-02

2.3.0 → 3.0.02016-02-03

### Community

Maintainers

![](https://www.gravatar.com/avatar/0e5ac8b2dcb292a173c9e56c800e09f880a4ee6240e0ee3af4e96aa76521f1cf?d=identicon)[kongkannika](/maintainers/kongkannika)

---

Top Contributors

[![josegonzalez](https://avatars.githubusercontent.com/u/65675?v=4)](https://github.com/josegonzalez "josegonzalez (88 commits)")[![ADmad](https://avatars.githubusercontent.com/u/142658?v=4)](https://github.com/ADmad "ADmad (20 commits)")[![joshuapaling](https://avatars.githubusercontent.com/u/145042?v=4)](https://github.com/joshuapaling "joshuapaling (10 commits)")[![martonmiklos](https://avatars.githubusercontent.com/u/1609182?v=4)](https://github.com/martonmiklos "martonmiklos (9 commits)")[![dereuromark](https://avatars.githubusercontent.com/u/39854?v=4)](https://github.com/dereuromark "dereuromark (7 commits)")[![kongka](https://avatars.githubusercontent.com/u/22835948?v=4)](https://github.com/kongka "kongka (6 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)")[![DIDoS](https://avatars.githubusercontent.com/u/5557268?v=4)](https://github.com/DIDoS "DIDoS (3 commits)")[![ckeboss](https://avatars.githubusercontent.com/u/723809?v=4)](https://github.com/ckeboss "ckeboss (3 commits)")[![mozillamonks](https://avatars.githubusercontent.com/u/130826?v=4)](https://github.com/mozillamonks "mozillamonks (2 commits)")[![styks1111](https://avatars.githubusercontent.com/u/642930?v=4)](https://github.com/styks1111 "styks1111 (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)")[![gaurish](https://avatars.githubusercontent.com/u/235844?v=4)](https://github.com/gaurish "gaurish (1 commits)")[![hdogan](https://avatars.githubusercontent.com/u/777820?v=4)](https://github.com/hdogan "hdogan (1 commits)")[![HowardBraham](https://avatars.githubusercontent.com/u/539738?v=4)](https://github.com/HowardBraham "HowardBraham (1 commits)")[![k1LoW](https://avatars.githubusercontent.com/u/57114?v=4)](https://github.com/k1LoW "k1LoW (1 commits)")[![plazareff](https://avatars.githubusercontent.com/u/239725?v=4)](https://github.com/plazareff "plazareff (1 commits)")

---

Tags

exportcakephpcsvview

### Embed Badge

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

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

###  Alternatives

[friendsofcake/cakephp-csvview

A CSV View class for CakePHP

1782.6M5](/packages/friendsofcake-cakephp-csvview)[cakephp/bake

Bake plugin for CakePHP

11212.0M196](/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.3M41](/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)

PHPackages © 2026

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