PHPackages                             vkr/csv-bundle - 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. [PDF &amp; Document Generation](/categories/documents)
4. /
5. vkr/csv-bundle

ActiveSymfony-bundle[PDF &amp; Document Generation](/categories/documents)

vkr/csv-bundle
==============

A bundle for CSV file creation in Symfony2/3

1.0.3(8y ago)0208MITPHPPHP &gt;=5.6

Since Jul 16Pushed 8y ago1 watchersCompare

[ Source](https://github.com/wladislavk/CSVBundle)[ Packagist](https://packagist.org/packages/vkr/csv-bundle)[ Docs](https://github.com/wladislavk/CSVBundle)[ RSS](/packages/vkr-csv-bundle/feed)WikiDiscussions master Synced 2mo ago

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

About
=====

[](#about)

This is a simple bundle for CSV creation in Symfony. It doesn't have any configuration and no dependencies except for Symfony, however it works best if you use Doctrine and want to parse a query result into CSV format.

Installation
============

[](#installation)

Nothing to install except enabling the bundle in `AppKernel.php`.

Usage
=====

[](#usage)

Basic usage
-----------

[](#basic-usage)

First, you need to have some kind of data source. This bundle is very flexible about how your data source looks - basically, it has to be an array or array-like object (anything that works with `foreach`), and its elements can be either arrays or objects. In other words, it will work with any non-null value that is returned by Doctrine's `getResult()`or `getArrayResult()`.

You also need to define fields that will make it into your CSV. If your data source consists of arrays, those fields are just keys of those arrays. If you work with objects, field names must comply with the following rule with respect to the object's public getters:

```
$fieldName = lcfirst(str_replace('get', '', $getterName));

```

Once you have a data source and field names, you can form the CSV data in your controller:

```
$dataSource = [
    [
        'name' => 'name1',
        'value' => 'value1',
        'foo' => 'bar',
    ]
];
$fields = ['name', 'value'];
$CSVCreator = $this->get('vkr_csv.csv_creator');
$CSVData = $CSVCreator->parseDataToCSV($dataSource, $fields);

```

The variable `$CSVData` will hold the following string:

```
name,value\n
name1,value1\n

```

If there are any commas in the data source values, those will be swapped for whitespaces.

Field labels
------------

[](#field-labels)

If you want to create 'nice' titles for the first row of your CSV, you can use the third argument of `parseDataToCSV()`, array of field labels. If it is not empty, it should contain the same number of elements as `$fields`. For example:

```
$dataSource = [
    [
        'element_name' => 'name1',
        'element_value' => 'value1',
    ]
];
$fields = ['element_name', 'element_value'];
$fieldLabels = ['Element name', 'Element value'];
$CSVData = $CSVCreator->parseDataToCSV($dataSource, $fields, $fieldLabels);

```

The resulting data will look as follows:

```
Element name, Element value\n
name1,value1\n

```

Note that neither `$fields` nor `$fieldLabels` can normally contain separator symbols, otherwise `MalformedCSVFieldsException` will be thrown. However, if you define a field with a separator symbol and a corresponding label without the separator, the script will work as usual:

```
$separator = '-';
$fields = ['my-value'];
$fieldLabels = ['My value'];

```

Custom separators
-----------------

[](#custom-separators)

If you want to use something else than comma as a separator, you can specify the fourth argument of `parseDataToCSV()`. You can also change the separator replacement string by specifying the fifth argument. Note that separator replacement cannot occur in both field names and field labels.

```
$dataSource = [
    [
        'name' => 'name 1',
        'value' => 'value 1',
    ]
];
$fields = ['name', 'value'];
$separator = ' ';
$replacement = '_';
$CSVData = $CSVCreator->parseDataToCSV($dataSource, $fields, [], $separator, $replacement);

```

The resulting data will look as follows:

```
name value\n
name_1 value_1\n

```

Handling dates inside data
--------------------------

[](#handling-dates-inside-data)

If an element of your data source cannot be implicitly converted to string, the bundle will throw `MalformedCSVObjectException`. The only exception to this are `DateTime`objects that are frequently returned by Doctrine. If you expect to receive a `DateTime`object, you should specify the sixth argument of `parseDataToCSV()` which should be a format string that is accepted by `DateTime::format()` method.

```
$dataSource = [
    [
        'name' => 'name1',
        'date' => new DateTime('2016-02-01'),
    ]
];
$fields = ['name', 'date'];
$format = 'd/m/Y';
$CSVData = $CSVCreator->parseDataToCSV($dataSource, $fields, [], null, null, $format);

```

The resulting data will look as follows:

```
name,date\n
name1,01/02/2016\n

```

If the format string contains separator symbols, those will be replaced as well.

If you did not specify the sixth argument or it is malformed, the bundle will not give you any errors, rather you will get a standard result of calling `DateTime::format()`without arguments, that will depend on your PHP settings.

Fillers
-------

[](#fillers)

The seventh, and final argument of `parseDataToCSV()` determines what to do if the field value on one or more of elements of your data source is null or undefined. If this argument is not specified, an empty string is returned. For example:

```
$dataSource = [
    [
        'name' => 'name1',
    ]
];
$fields = ['name', 'price'];
$CSVData = $CSVCreator->parseDataToCSV($dataSource, $fields);

```

The resulting data without `$filler` look as follows:

```
name,price\n
name1,\n

```

If you specify that

```
$filler = '0.00';

```

you will get this:

```
name,price\n
name1,0.00\n

```

Separator symbols inside fillers will be replaced.

Forming CSV file from data
--------------------------

[](#forming-csv-file-from-data)

The variable returned by `parseDataToCSV()` is not yet a CSV file, it is just a string. To make Symfony return a file, you need to define headers and return a response. This bundle includes a simple helper function for header definition, `setHeaders()`. It accepts an optional `$filename` argument which is a file name without extension. If this argument is not specified, the file will be called `{current_timestamp}.csv`.

Here is how you return a file from the controller:

```
$headers = $CSVCreator->setHeaders('foo');
$response = new Symfony\Component\HttpFoundation\Response();
foreach ($headers as $headerName => $headerValue) {
    $response->headers->set($headerName, $headerValue);
}
$response->setContent($CSVData);
return $response;

```

The resulting file will be named `foo.csv`.

API
===

[](#api)

*string CSVCreator::parseDataToCSV(array|Traversable $dataSource, string\[\] $fields, string\[\] $fieldLabels = \[\], string $separator = ',', string $replacement = ' ', string $dateFormat = '', string $filler = '')*

*string\[\] CSVCreator::setHeaders(string $filename = '')*

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity11

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity61

Established project with proven stability

 Bus Factor1

Top contributor holds 100% 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 ~106 days

Total

4

Last Release

3269d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/79f5fa971e7fda7a6180c1bdfca4f819a43b7681ec4e04c66b184a082fb5a20f?d=identicon)[wladislavk](/maintainers/wladislavk)

---

Top Contributors

[![wladislavk](https://avatars.githubusercontent.com/u/11371476?v=4)](https://github.com/wladislavk "wladislavk (8 commits)")

---

Tags

Symfony2csvsymfony3

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/vkr-csv-bundle/health.svg)

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

###  Alternatives

[maatwebsite/excel

Supercharged Excel exports and imports in Laravel

12.7k144.3M712](/packages/maatwebsite-excel)[league/csv

CSV data manipulation made easy in PHP

3.5k166.1M646](/packages/league-csv)[rap2hpoutre/fast-excel

Fast Excel import/export for Laravel

2.3k24.9M47](/packages/rap2hpoutre-fast-excel)[openspout/openspout

PHP Library to read and write spreadsheet files (CSV, XLSX and ODS), in a fast and scalable way

1.1k57.6M131](/packages/openspout-openspout)[sonata-project/exporter

Lightweight Exporter library

44920.9M35](/packages/sonata-project-exporter)[gotenberg/gotenberg-php

A PHP client for interacting with Gotenberg, a developer-friendly API for converting numerous document formats into PDF files, and more!

3685.2M19](/packages/gotenberg-gotenberg-php)

PHPackages © 2026

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