PHPackages                             avro/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. avro/csv-bundle

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

avro/csv-bundle
===============

Symfony2 CSV Bundle

v1.0.1(4y ago)3040.5k↓23.1%12[2 issues](https://github.com/jdewit/AvroCsvBundle/issues)[2 PRs](https://github.com/jdewit/AvroCsvBundle/pulls)1MITPHPPHP ^7.1 || ^8.0CI failing

Since Dec 14Pushed 4y ago4 watchersCompare

[ Source](https://github.com/jdewit/AvroCsvBundle)[ Packagist](https://packagist.org/packages/avro/csv-bundle)[ Docs](http://github.com/jdewit/AvroCsvBundle)[ RSS](/packages/avro-csv-bundle/feed)WikiDiscussions master Synced yesterday

READMEChangelog (10)Dependencies (9)Versions (25)Used By (1)

AvroCsvBundle [![Build Status](https://camo.githubusercontent.com/049497afa51853442e2a5f793ee8253f77c1e251f5ac04610640ba3dafb248d5/68747470733a2f2f7472617669732d63692e6f72672f6a64657769742f4176726f43737642756e646c652e706e673f6272616e63683d6d6173746572)](https://travis-ci.org/jdewit/AvroCsvBundle)
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

[](#avrocsvbundle-)

This bundle provides an easy way to upload data to your db using csv files with just a few configuration parameters.

Status
------

[](#status)

This bundle is under development and may break.

Limitations
-----------

[](#limitations)

This bundle uses php and Doctrine2 and is not your best bet for importing gargantuan csv files. Use your databases native importing &amp; exporting solutions to skin that cat.

Features
--------

[](#features)

- Import data by csv file
- Export data to csv file
- A few services for reading/writing csv files

Supports
--------

[](#supports)

- Doctrine ORM

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

[](#installation)

This bundle is listed on packagist.

Simply add it to your apps composer.json file

```
    "avro/csv-bundle": "^0.4.2"
```

Enable the bundle in config/bundles.php as well as the dependent AvroCaseBundle:

```
    Avro\CsvBundle\AvroCsvBundle::class => ['all' => true],
    Avro\CaseBundle\AvroCaseBundle::class => ['all' => true],
```

Configuration
-------------

[](#configuration)

Add this required config

```
# config/packages/avro_csv.yaml
avro_csv:
    db_driver: orm # supports orm
    batch_size: 15 # The batch size between flushing & clearing the doctrine object manager
    tmp_upload_dir: "%kernel.root_dir%/../web/uploads/tmp/" # The directory to upload the csv files to
    sample_count: 5 # The number of sample rows to show during mapping
```

Add routes to your config

```
# config/routes/avro_csv.yaml
avro_csv:
    resource: "@AvroCsvBundle/Resources/config/routing.yml"
```

Add the entities/documents you want to implement importing/exporting for

```
# config/packages/avro_csv.yaml
avro_csv:
    #
    objects: # the entities/documents you want to be able to import/export data with
        client:
            class: Avro\CrmBundle\Entity\Client # The entity/document class
            redirect_route: avro_crm_client_list # The route to redirect to after import
        invoice:
            class: Avro\CrmBundle\Entity\Invoice
            redirect_route: avro_crm_invoice_list
```

To exclude certain fields from being mapped, use the ImportExclude annotation like so.

```
namespace Avro\CrmBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Avro\CsvBundle\Annotation\ImportExclude;

/**
 * Avro\CrmBundle\Entity\Client
 *
 * @ORM\Entity
 */
class Client
{
    /**
     * @var string
     *
     * @ORM\Column(type="string", length=100, nullable=true)
     * @ImportExclude
     */
    protected $password;
```

Importing
---------

[](#importing)

Implement importing for as many entities/documents as you like. All you have to do is add them to the objects node as mentioned previously.

Then just include a link to specific import page like so:

```
Go to import page
```

Replace "client" with whatever alias you called your entity/document in the config.

Views
-----

[](#views)

The bundle comes with some basic twitter bootstrap views that you can override by extending the bundle.

Association mapping
-------------------

[](#association-mapping)

An event is fired when importing an association field to allow implementing your own logic fitting

Just create a custom listener in your app that listens for the `AssociationFieldEvent::class` event.

A simple implementation getting an associated entity by name could look like:

```
namespace App\EventListener;

use Avro\CsvBundle\Event\AssociationFieldEvent;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Csv import listener
 */
class ImportListener implements EventSubscriberInterface
{
    private $em;

    /**
     * @param EntityManagerInterface   $em      The entity manager
     */
    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    public static function getSubscribedEvents()
    {
        return [
            AssociationFieldEvent::class => 'importAssociation',
        ];
    }

    /**
     * Set the objects createdBy field
     *
     * @param AssociationFieldEvent $event
     */
    public function importAssociation(AssociationFieldEvent $event)
    {
        $association = $event->getAssociationMapping();
        switch ($association['type']) {
            case ClassMetadataInfo::ONE_TO_ONE:
            case ClassMetadataInfo::MANY_TO_ONE:
                $relation = $this->em->getRepository($association['targetEntity'])->findOneBy(
                    [
                        'name' => $event->getRow()[$event->getIndex()],
                    ]
                );
                if ($relation) {
                    $event->getObject()->{'set'.ucfirst($association['fieldName'])}($relation);
                }
                break;
        }
    }
}
```

Customizing each row
--------------------

[](#customizing-each-row)

Want to customize certain fields on each row? No problem.

An event is fired when a row is added that you can tap into to customize each row of data.

Just create a custom listener in your app that listens for the `RowAddedEvent::class` event.

For example...

```
namespace App\EventListener;

use Avro\CsvBundle\Event\RowAddedEvent;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\SecurityContextInterface;

/**
 * Csv import listener
 */
class ImportListener implements EventSubscriberInterface
{
    private $em;
    private $context;

    /**
     * @param EntityManagerInterface   $em      The entity manager
     * @param SecurityContextInterface $context The security context
     */
    public function __construct(EntityManagerInterface $em, SecurityContextInterface $context)
    {
        $this->em = $em;
        $this->context = $context;
    }

    public static function getSubscribedEvents()
    {
        return [
            RowAddedEvent::class => 'setCreatedBy',
        ];
    }

    /**
     * Set the objects createdBy field
     *
     * @param RowAddedEvent $event
     */
    public function setCreatedBy(RowAddedEvent $event)
    {
        $object = $event->getObject();

        $user = $this->context->getToken()->getUser();

        $object->setCreatedBy($user);
    }
}
```

Register your listener or use autowiring

Exporting
---------

[](#exporting)

This bundle provides some simple exporting functionality.

Navigating to "/export/your-alias" will export all of your data to a csv and allow you to download it from the browser.

You can customize the export query builder and the exported data by listening to the corresponding events (See events in the `Avro\CsvBundle\Event` namespace).

If you want to customize data returned, just create your own controller action and grab the queryBuilder from the exporter and add your constraints before calling "getContent()".

Ex.

```
namespace App\Controller;

use Avro\CsvBundle\Export\ExporterInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;

class ExportController extends AbstractController
{
    /**
     * Export a db table.
     *
     * @param ExporterInterface $exporter The exporter
     * @param string            $alias    The objects alias
     *
     * @return Response
     */
    public function exportAction(ExporterInterface $exporter, string $alias): Response
    {
        $class = $this->getParameter(sprintf('avro_csv.objects.%s.class', $alias));

        $exporter->init($class);

        // customize the query
        $qb = $exporter->getQueryBuilder();
        $qb->where('o.fieldName =? 1')->setParameter(1, false);

        $content = $exporter->getContent();

        $response = new Response($content);
        $response->headers->set('Content-Type', 'application/csv');
        $response->headers->set('Content-Disposition', sprintf('attachment; filename="%s.csv"', $alias));

        return $response;
    }
}
```

Register your controller or use your already setup autowiring

To Do:
------

[](#to-do)

- Finish mongodb support

Acknowledgements
----------------

[](#acknowledgements)

Thanks to jwage's [EasyCSV](https://github.com/jwage/EasyCSV) for some ground work.

Feedback and pull requests are much appreciated!

###  Health Score

43

—

FairBetter than 89% of packages

Maintenance19

Infrequent updates — may be unmaintained

Popularity39

Limited adoption so far

Community20

Small or concentrated contributor base

Maturity78

Established project with proven stability

 Bus Factor1

Top contributor holds 53.3% 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 ~148 days

Recently: every ~95 days

Total

23

Last Release

1683d ago

Major Versions

v0.5.1 → v1.0.02021-11-22

PHP version history (6 changes)v0.1.0PHP &gt;=5.3.2

0.1.x-devPHP &gt;=5.3.2|&lt;7.0

v0.2.0PHP ^5.5.9|&gt;=7.0.8

v0.3.0PHP ^7.1.3

v0.4.0PHP ^7.2.0

v1.0.0PHP ^7.1 || ^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/8b43556a54d880ffb06c69ff48a730a1b6126d04cba4749ab7040723ba706407?d=identicon)[jdewit](/maintainers/jdewit)

---

Top Contributors

[![jdewit](https://avatars.githubusercontent.com/u/467498?v=4)](https://github.com/jdewit "jdewit (48 commits)")[![MisatoTremor](https://avatars.githubusercontent.com/u/3536384?v=4)](https://github.com/MisatoTremor "MisatoTremor (36 commits)")[![aur1mas](https://avatars.githubusercontent.com/u/123205?v=4)](https://github.com/aur1mas "aur1mas (3 commits)")[![garak](https://avatars.githubusercontent.com/u/179866?v=4)](https://github.com/garak "garak (2 commits)")[![krizon](https://avatars.githubusercontent.com/u/880695?v=4)](https://github.com/krizon "krizon (1 commits)")

---

Tags

exportcsvimport

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[maatwebsite/excel

Supercharged Excel exports and imports in Laravel

12.9k157.3M893](/packages/maatwebsite-excel)[league/csv

CSV data manipulation made easy in PHP

3.5k182.1M859](/packages/league-csv)[goodby/csv

CSV import/export library

9865.7M25](/packages/goodby-csv)[handcraftedinthealps/goodby-csv

CSV import/export library

441.8M7](/packages/handcraftedinthealps-goodby-csv)[ufirst/lang-import-export

A Laravel package providing artisan commands to import and export language files from and to CSV.

42229.7k](/packages/ufirst-lang-import-export)[shuchkin/simplecsv

Parse and retrieve data from CSV files. Export data to CSV.

52100.9k](/packages/shuchkin-simplecsv)

PHPackages © 2026

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