PHPackages                             stilliard/csvparser - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. stilliard/csvparser

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

stilliard/csvparser
===================

csv manipulation made simple

v1.4.4(4mo ago)1137.8k↓31%5[11 issues](https://github.com/stilliard/CsvParser/issues)MITPHPCI passing

Since Sep 9Pushed 3mo ago3 watchersCompare

[ Source](https://github.com/stilliard/CsvParser)[ Packagist](https://packagist.org/packages/stilliard/csvparser)[ GitHub Sponsors](https://github.com/stilliard)[ RSS](/packages/stilliard-csvparser/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (1)Versions (23)Used By (0)

Csv Parser
==========

[](#csv-parser)

Quickly take in and output csv formats.

[![Build Status](https://camo.githubusercontent.com/a6311938d833b94f4bb5bcaaf548dd104209fb0656c17858d7a2fd41f21bd1f3/68747470733a2f2f7472617669732d63692e6f72672f7374696c6c696172642f4373765061727365722e706e673f6272616e63683d6d6173746572)](https://travis-ci.org/stilliard/CsvParser)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/cd6a1dac8c858081865a9cd26611e82ef2976a438478a3c29460d16e1cca8daa/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f7374696c6c696172642f4373765061727365722f6261646765732f7175616c6974792d73636f72652e706e673f733d33663832316433323331643738653836633431633963643932313363363866313634626235336436)](https://scrutinizer-ci.com/g/stilliard/CsvParser/)[![Code Coverage](https://camo.githubusercontent.com/46290fc1fd77de5d83455473e83f088db95c50dce53732b2aa5f714cbf69f51e/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f7374696c6c696172642f4373765061727365722f6261646765732f636f7665726167652e706e673f733d64626339643931623736376238346131613634396235363935623861336364636536393036383461)](https://scrutinizer-ci.com/g/stilliard/CsvParser/)[![Latest Stable Version](https://camo.githubusercontent.com/d8868f71e84767d14aaf1132a9c573bda7e5fdcf6581cbe0cad06554a16d2a7e/68747470733a2f2f706f7365722e707567782e6f72672f7374696c6c696172642f6373767061727365722f762f737461626c652e706e67)](https://packagist.org/packages/stilliard/csvparser) [![Total Downloads](https://camo.githubusercontent.com/40445ce6924895df332e2f26f86320fc65e9607644e71300471dd6c1085f358f/68747470733a2f2f706f7365722e707567782e6f72672f7374696c6c696172642f6373767061727365722f646f776e6c6f6164732e706e67)](https://packagist.org/packages/stilliard/csvparser) [![Latest Unstable Version](https://camo.githubusercontent.com/6ad723c882fd8b7942868482bc2cb3fc597b123bdea1cac3bc0e6d24b4c3e460/68747470733a2f2f706f7365722e707567782e6f72672f7374696c6c696172642f6373767061727365722f762f756e737461626c652e706e67)](https://packagist.org/packages/stilliard/csvparser) [![License](https://camo.githubusercontent.com/73fcf3af65cc49d8047d5116cdbb34bf917747f4a37605baedda0d94ad43f73f/68747470733a2f2f706f7365722e707567782e6f72672f7374696c6c696172642f6373767061727365722f6c6963656e73652e706e67)](https://packagist.org/packages/stilliard/csvparser)[![FOSSA Status](https://camo.githubusercontent.com/73228c6d4ebe3f669e1cdbe21de83c4b520b0a866b318c9562b78440ec0c6148/68747470733a2f2f6170702e666f7373612e696f2f6170692f70726f6a656374732f6769742532426769746875622e636f6d2532467374696c6c696172642532464373765061727365722e7376673f747970653d736869656c64)](https://app.fossa.io/projects/git%2Bgithub.com%2Fstilliard%2FCsvParser?ref=badge_shield)

Install
-------

[](#install)

```
composer require stilliard/csvparser 1.4.4
```

Example usage:
--------------

[](#example-usage)

```
use CsvParser\Parser;
//
// Simple array to string usage
//
$array = [['id'=>1, 'name'=>'Bob'],['id'=>2, 'name'=>'Bill']];
$parser = new Parser();
$csv = $parser->fromArray($array);
var_dump($parser->toString($csv));
```

Example stream reading (better memory optimisations)
----------------------------------------------------

[](#example-stream-reading-better-memory-optimisations)

```
// stream reading from a CSV file
foreach (Parser::stream(__DIR__ . '/your/path/input.csv') as $row) {
    var_dump($row);
}
// write file
Parser::write($data, __DIR__ . '/your/path/output.csv');
```

```
//
// Full power examples:
//

// setup initial parser
$parser = new \CsvParser\Parser(',', '"', "\n");

// change settings after init
// set column delimiter
$parser->fieldDelimiter = ';';
// set text enclosure
$parser->fieldEnclosure = "'";
// set line delimiter
$parser->lineDelimiter = "\n";

// Input (returns instance of \CsvParser\Csv)
$csv = $parser->fromArray([['id'=>1, 'name'=>'Bob'],['id'=>2, 'name'=>'Bill']]);
$csv = $parser->fromString("id,name\n1,Bob\n2,Bill");
$csv = $parser->fromFile('demo.csv');

// get row count
var_dump($csv->getRowCount());

// get the first row as array from the csv
var_dump($csv->first());

// get the column headings / keys
var_dump($csv->getKeys());

// want to force a column sort / index?
$csv->reKey(['id', 'name', 'email']);

// append/prepend rows
$csv->appendRow(['id'=>3, 'name'=>'Ben']);
$csv->prependRow(['id'=>4, 'name'=>'Barry']);

// map function over column
$csv->mapColumn('name', 'trim');
$csv->mapColumn('name', function ($name) {
    return trim($name);
});

// map function over rows
$csv->mapRows(function ($row) {
    $row['codename'] = base64_encode($row['id']);
    return $row;
});

// add a column
$csv->addColumn('codename', 'default value');

// remove a column
$csv->removeColumn('codename');

// filter down rows
$csv->filterRows(function ($row) {
    return $row['id'] != '#'; // remove rows where the id column just has a hash inside
});

// remove row by index
$csv->removeRowByIndex(4);
// or remove row(s) by column value, such as id 22
$csv->removeRow('id', 22);
// or remove row(s) by multiple creiteria, such as when id 22 AND when name is 'some name'
$csv->removeRows(['id'=>22, 'name'=>'some name']);

// Column reordering
$csv->reorderColumn('colname', 0); // move to position 0 (the start)
// or multiple
$csv->reorderColumns(['colname1'=>0, 'colname2'=>4]);

// Row reordering
// to move the row with id of 22 to the start
$csv->reorderRow('id', 22, 0);
// or move id 22 to the start, and id 5 after it
$csv->reorderRows('id', [22 => 0, 5 => 1]);

// Sort rows by a column
$csv->reorderRowsByColumn('id', 'desc');
// or even multiples:
$csv->reorderRowsByColumns(['name', 'id' => 'desc']);

// Output
var_dump($parser->toArray($csv));
var_dump($parser->toString($csv));
var_dump($parser->toFile($csv, 'demo.csv')); // file was created?

// Need to chunk into multiple chunks/files?
$chunks = $parser->toChunks($csv, 1000);
foreach ($chunks as $i => $chunk) {
    $parser->toFile($chunk, "output-{$i}.csv");
}

// Remove duplicates
$csv->removeDuplicates('email');

// Remove blanks
$csv->removeBlanks('email');
```

Writing CSV as a Stream
-----------------------

[](#writing-csv-as-a-stream)

The `writeStream` method allows you to write CSV data as a stream. This can be useful for writing large datasets efficiently.

### Example: Writing to a File

[](#example-writing-to-a-file)

```
use CsvParser\Parser;

$file = fopen('output.csv', 'w');

$callback = function () {
    static $data = [
        ['name' => 'John', 'age' => 30],
        ['name' => 'Jane', 'age' => 25],
        ['name' => 'Doe', 'age' => 40],
    ];
    return array_shift($data);
};

Parser::writeStream($file, ['name', 'age'], $callback);

fclose($file);
```

### Example: Writing to the Screen

[](#example-writing-to-the-screen)

```
use CsvParser\Parser;

$resource = fopen('php://output', 'w');

$callback = function () {
    $data = [
        ['name' => 'John', 'age' => 30],
        ['name' => 'Jane', 'age' => 25],
        ['name' => 'Doe', 'age' => 40],
    ];
    foreach ($data as $row) {
        yield $row;
    }
};

Parser::writeStream($resource, ['name', 'age'], $callback);

fclose($resource);
```

### Example: Writing from a PDO Fetch

[](#example-writing-from-a-pdo-fetch)

```
use CsvParser\Parser;
use PDO;

$pdo = new PDO('mysql:host=localhost;dbname=testdb', 'username', 'password');
$stmt = $pdo->query('SELECT name, age FROM users');

$file = fopen('output.csv', 'w');

Parser::writeStream($file, ['name', 'age'], fn() => $stmt->fetch(PDO::FETCH_NUM));

fclose($file);
```

In this example, the `callback` function uses a PDO statement to fetch rows from a database. The `writeStream` method will continue to call the `callback` until it returns `false`.

Test
----

[](#test)

To run the tests, you can use PHPUnit. Make sure you have PHPUnit installed and then run:

```
phpunit .
```

Middleware
----------

[](#middleware)

You can use middleware to modify data as it is read or written.

### Available Middleware

[](#available-middleware)

- **FormulaInjectionMiddleware**: Protects against formula injection (CSV Injection) by escaping characters that could be interpreted as formulas.
- **DatetimeMiddleware**: Detects dates and adds an escape character so that spreadsheet apps don't auto-convert formats.
- **EncodingCheckMiddleware**: Validates input encoding (default UTF-8) and can warn, throw exception, or attempt to fix invalid encoding. It can also fix "mojibake" (double-encoded text).

### Usage

[](#usage)

```
use CsvParser\Parser;
use CsvParser\Middleware\FormulaInjectionMiddleware;
use CsvParser\Middleware\DatetimeMiddleware;
use CsvParser\Middleware\TextFieldMiddleware;
use CsvParser\Middleware\EncodingCheckMiddleware;

$parser = new Parser();

// Protect against CSV formula injection
$parser->addMiddleware(new FormulaInjectionMiddleware());

// Escape date/datetime fields to prevent auto-conversion
$parser->addMiddleware(new DatetimeMiddleware());

// Escape specific text fields
$parser->addMiddleware(new TextFieldMiddleware([
    'fields' => ['long_id', 'phone_number'],
]);

// Encoding check options:
// action: 'warn' (default), 'throw', or 'fix'
// fixMojibake: true/false (default false) - attempts to fix double-encoded text (e.g. Ã© -> é)
$parser->addMiddleware(new EncodingCheckMiddleware([
    'action' => 'warn',
    'fixMojibake' => true,
]));

// ... use parser as normal
```

See the [`MiddlewareTest.php`](test/MiddlewareTest.php) file for more usage examples.

License
-------

[](#license)

[![FOSSA Status](https://camo.githubusercontent.com/7674a25802cfe70221a0b61027536146b9146e78b8d95d879585c81977c06501/68747470733a2f2f6170702e666f7373612e696f2f6170692f70726f6a656374732f6769742532426769746875622e636f6d2532467374696c6c696172642532464373765061727365722e7376673f747970653d6c61726765)](https://app.fossa.io/projects/git%2Bgithub.com%2Fstilliard%2FCsvParser?ref=badge_large)

###  Health Score

49

—

FairBetter than 95% of packages

Maintenance58

Moderate activity, may be stable

Popularity36

Limited adoption so far

Community15

Small or concentrated contributor base

Maturity73

Established project with proven stability

 Bus Factor1

Top contributor holds 95.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 ~218 days

Recently: every ~0 days

Total

20

Last Release

126d ago

### Community

Maintainers

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

---

Top Contributors

[![stilliard](https://avatars.githubusercontent.com/u/77454?v=4)](https://github.com/stilliard "stilliard (112 commits)")[![james-mckinnon](https://avatars.githubusercontent.com/u/3246228?v=4)](https://github.com/james-mckinnon "james-mckinnon (3 commits)")[![fossabot](https://avatars.githubusercontent.com/u/29791463?v=4)](https://github.com/fossabot "fossabot (1 commits)")[![scrutinizer-auto-fixer](https://avatars.githubusercontent.com/u/6253494?v=4)](https://github.com/scrutinizer-auto-fixer "scrutinizer-auto-fixer (1 commits)")

---

Tags

csv-formatphp

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/stilliard-csvparser/health.svg)

```
[![Health](https://phpackages.com/badges/stilliard-csvparser/health.svg)](https://phpackages.com/packages/stilliard-csvparser)
```

###  Alternatives

[tenancy/tenancy

Creating multi tenant saas from your Laravel app with ease

1.3k43.6k](/packages/tenancy-tenancy)[tunezilla/dynamic-action-fields

Dynamic Action Fields for Laravel Nova

18111.9k](/packages/tunezilla-dynamic-action-fields)[igorsgm/laravel-git-hooks

🪝• Efficiently manage Git hooks in Laravel projects. Enhance code quality, save time on reviews, and prevent bugs from entering your repository.

2931.7k1](/packages/igorsgm-laravel-git-hooks)

PHPackages © 2026

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