PHPackages                             pieceofcake2/csv-view - 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. pieceofcake2/csv-view

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

pieceofcake2/csv-view
=====================

A CSV View class for CakePHP 2.x

v2.3.1(7mo ago)00MITPHPPHP &gt;=8.0CI passing

Since Oct 10Pushed 7mo agoCompare

[ Source](https://github.com/pieceofcake2/csv-view)[ Packagist](https://packagist.org/packages/pieceofcake2/csv-view)[ RSS](/packages/pieceofcake2-csv-view/feed)WikiDiscussions 2.x Synced 1mo ago

READMEChangelogDependencies (7)Versions (2)Used By (0)

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

[](#csvview-plugin)

[![GitHub License](https://camo.githubusercontent.com/bb7c53d85cacd044a1d342fba522c2cb4f02ff8231ad871091fb971244458b0e/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f70696563656f6663616b65322f6373762d766965773f6c6162656c3d4c6963656e7365)](LICENSE)[![Packagist Version](https://camo.githubusercontent.com/ef7977550082507980d1749fef0e72fcde3e990747e6f5a98cde9290ec6eff3c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f70696563656f6663616b65322f6373762d766965773f6c6162656c3d5061636b6167697374)](https://packagist.org/packages/pieceofcake2/csv-view)[![PHP](https://camo.githubusercontent.com/9aceaad994e938e55d819315c0faa53b8f77c7319dde6af29c5f1e976ad881d3/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646570656e64656e63792d762f70696563656f6663616b65322f6373762d766965772f7068703f6c6f676f3d706870266c6f676f436f6c6f723d253233464646464646266c6162656c3d504850266c6162656c436f6c6f723d25323337373742423426636f6c6f723d253233464646464646)](https://camo.githubusercontent.com/9aceaad994e938e55d819315c0faa53b8f77c7319dde6af29c5f1e976ad881d3/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646570656e64656e63792d762f70696563656f6663616b65322f6373762d766965772f7068703f6c6f676f3d706870266c6f676f436f6c6f723d253233464646464646266c6162656c3d504850266c6162656c436f6c6f723d25323337373742423426636f6c6f723d253233464646464646)[![CakePHP](https://camo.githubusercontent.com/5b76cf4c67203c1986e341c220c2f23d18379ddb18954fcd4a596fa011cc644e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646570656e64656e63792d762f70696563656f6663616b65322f6373762d766965772f70696563656f6663616b65322f63616b657068703f6c6f676f3d63616b65706870266c6f676f436f6c6f723d253233464646464646266c6162656c3d43616b65504850266c6162656c436f6c6f723d25323344333343343326636f6c6f723d253233464646464646)](https://camo.githubusercontent.com/5b76cf4c67203c1986e341c220c2f23d18379ddb18954fcd4a596fa011cc644e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646570656e64656e63792d762f70696563656f6663616b65322f6373762d766965772f70696563656f6663616b65322f63616b657068703f6c6f676f3d63616b65706870266c6f676f436f6c6f723d253233464646464646266c6162656c3d43616b65504850266c6162656c436f6c6f723d25323344333343343326636f6c6f723d253233464646464646)[![CI](https://camo.githubusercontent.com/2f3897d68a98e60b2a289a8e11268c07ab7192f16723e3eced2f97db5e7b4a42/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f70696563656f6663616b65322f6373762d766965772f43492e796d6c3f6c6162656c3d4349)](https://github.com/pieceofcake2/csv-view/actions/workflows/CI.yml)[![Codecov](https://camo.githubusercontent.com/b92a432b0bc29cea41ab3557195ff59bbc5534d2a86cc47343db0e7c8a626a24/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f67682f70696563656f6663616b65322f6373762d766965773f6c6162656c3d436f766572616765)](https://codecov.io/gh/pieceofcake2/csv-view)

**This is forked for CakePHP2.**

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 2.12+
- PHP8.0+

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

[](#installation)

```
composer require pieceofcake2/csv-view
```

### Enable plugin

[](#enable-plugin)

In 2.0 you need to enable the plugin your `app/Config/bootstrap.php` file:

```
    CakePlugin::load('CsvView');
```

If you are already using `CakePlugin::loadAll();`, then this is not necessary.

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->viewClass = '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->viewClass = '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->viewClass = '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->viewClass = 'CsvView.Csv';
    $this->set(compact('data', '_serialize', '_delimiter', '_enclosure', '_newline', '_eol'));
}
```

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 paths for each record. This is an array of `Hash::extract()`-compatible syntax:

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

    $this->viewClass = '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 'NULL'.

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

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

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

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

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

// Access /posts/export.csv to get the data as csv

For really complex CSVs, you can also simply use your own view files. This is only supported in 2.1+. 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 app/View/Posts/csv/export.ctp
public function export() {
    $posts = $this->Post->find('all');
    $_serialize = null;
    $this->viewClass = 'CsvView.Csv';
    $this->set(compact('posts', '_serialize');
}
```

#### 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`.

To set a custom file name, use the [`CakeResponse::download`](http://book.cakephp.org/2.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->download('my_file.csv'); // viewClass = 'CsvView.Csv';
    $this->set(compact('data', '_serialize'));
}
```

### CsvView Component Usage

[](#csvview-component-usage)

The CsvView component provides a few methods to help you quickly export the results of complex Model `find('all')` calls.

*Note:* nested `belongsTo` associations are handled no problem. Others (eg. `hasMany`) will be ignored (I can't see why you'd want them in a CSV export, or how you'd include them gracefully).

To use the component, include it in your Components array:

```
// In your controller:
public $components = ['CsvView.CsvView'];
```

The component has the following methods:

#### prepareExtractFromFindResults($data, $excludePaths = array())

[](#prepareextractfromfindresultsdata-excludepaths--array)

Recursively searches `$data` and returns an array of all unique `Hash::extract()`-compatible paths, suitable for the $\_extract variable

- *$data:* the results of a Model `find('all')` call.
- *$excludePaths (optional):* an array of paths to exclude from the returned array, using `Hash::extract()`-compatible syntax. Eg. `['MyModel.column_name']`

#### prepareHeaderFromExtract($extract, $customHeaders = array())

[](#prepareheaderfromextractextract-customheaders--array)

Returns an array of user-friendly colum titles, suitable for use as the `$_header`, based on the paths in `$extract`. Eg, the path 'City.Country.name' becomes 'Country Name'.

- *$extract:* an array of paths, using `Hash::extract()`-compatible syntax.
- *$customHeaders (optional):* an array of 'path' =&gt; 'Custom Title' pairs, eg. `['City.population' => 'No. of People']`. These custom headers, when specified, override the default generated headers.

#### quickExport($data, $excludePaths = array(), $customHeaders = array(), $includeHeader = true)

[](#quickexportdata-excludepaths--array-customheaders--array-includeheader--true)

Quickly export an the results of a Model `find('all')` call in one line of code.

- *$data* - the results of a Model `find('all')` call.
- *$excludePaths (optional):* Same use as in prepareExtractFromFindResults method, above
- *$customHeaders (optional):* Same use as in prepareHeaderFromExtract method, above
- *$includeHeader (optional):* if true, a $\_header will be included. Defaults to true.

*Example 1 - using quickExport, simplest use:*

```
$results = $this->MyModel->find('all');
$this->CsvView->quickExport($results);
```

*Example 2 - using quickExport, advanced use:*

```
$results = $this->MyModel->find('all');
$excludePaths = ['City.id', 'State.id', 'State.Country.id']; // Exclude all id fields
$customHeaders = ['City.population' => 'No. of People'];

$this->CsvView->quickExport($results, $excludePaths, $customHeaders);
```

*Example 3 - NOT using quickExport:*

```
$results = $this->MyModel->find('all');

$excludePaths = ['City.id', 'State.id', 'State.Country.id']; // Exclude all id fields
$_extract = $this->CsvView->prepareExtractFromFindResults($results, $excludePaths);

$customHeaders = ['City.population' => 'No. of People'];
$_header = $this->CsvView->prepareHeaderFromExtract($_extract, $customHeaders);

$_serialize = 'results';
$this->viewClass = 'CsvView.Csv';
$this->set(compact('results' ,'_serialize', '_header', '_extract'));
```

License
-------

[](#license)

See [LICENSE](LICENSE) for details.

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance64

Regular maintenance activity

Popularity0

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity40

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 65% 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 ~0 days

Total

2

Last Release

220d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/578548?v=4)[TSURU](/maintainers/ttsuru)[@ttsuru](https://github.com/ttsuru)

---

Top Contributors

[![josegonzalez](https://avatars.githubusercontent.com/u/65675?v=4)](https://github.com/josegonzalez "josegonzalez (52 commits)")[![joshuapaling](https://avatars.githubusercontent.com/u/145042?v=4)](https://github.com/joshuapaling "joshuapaling (10 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)")[![dereuromark](https://avatars.githubusercontent.com/u/39854?v=4)](https://github.com/dereuromark "dereuromark (2 commits)")[![ttsuru](https://avatars.githubusercontent.com/u/578548?v=4)](https://github.com/ttsuru "ttsuru (2 commits)")[![HowardBraham](https://avatars.githubusercontent.com/u/539738?v=4)](https://github.com/HowardBraham "HowardBraham (1 commits)")[![sakilimran](https://avatars.githubusercontent.com/u/3876178?v=4)](https://github.com/sakilimran "sakilimran (1 commits)")[![gaurish](https://avatars.githubusercontent.com/u/235844?v=4)](https://github.com/gaurish "gaurish (1 commits)")[![ajibarra](https://avatars.githubusercontent.com/u/794722?v=4)](https://github.com/ajibarra "ajibarra (1 commits)")[![chronon](https://avatars.githubusercontent.com/u/57735?v=4)](https://github.com/chronon "chronon (1 commits)")[![destinydriven](https://avatars.githubusercontent.com/u/358145?v=4)](https://github.com/destinydriven "destinydriven (1 commits)")[![ADmad](https://avatars.githubusercontent.com/u/142658?v=4)](https://github.com/ADmad "ADmad (1 commits)")[![hdogan](https://avatars.githubusercontent.com/u/777820?v=4)](https://github.com/hdogan "hdogan (1 commits)")

---

Tags

exportcakephpcsvviewcakephp2

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/pieceofcake2-csv-view/health.svg)

```
[![Health](https://phpackages.com/badges/pieceofcake2-csv-view/health.svg)](https://phpackages.com/packages/pieceofcake2-csv-view)
```

###  Alternatives

[friendsofcake/cakephp-csvview

A CSV View class for CakePHP

1762.5M3](/packages/friendsofcake-cakephp-csvview)[wyrihaximus/twig-view

Twig powered View for CakePHP

804.7M1](/packages/wyrihaximus-twig-view)[anourvalar/office

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

24085.2k](/packages/anourvalar-office)[dereuromark/cakephp-ajax

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

55255.9k1](/packages/dereuromark-cakephp-ajax)[dereuromark/cakephp-feed

A CakePHP plugin containing a RssView to generate RSS feeds.

1353.7k1](/packages/dereuromark-cakephp-feed)[dereuromark/cakephp-meta

A CakePHP plugin for SEO meta tags, OpenGraph and Twitter Cards

1012.9k1](/packages/dereuromark-cakephp-meta)

PHPackages © 2026

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