PHPackages                             philiprehberger/php-csv - 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. philiprehberger/php-csv

ActiveLibrary[PDF &amp; Document Generation](/categories/documents)

philiprehberger/php-csv
=======================

Memory-efficient CSV reader and writer with header mapping and type casting

v1.1.2(1mo ago)11[1 PRs](https://github.com/philiprehberger/php-csv/pulls)MITPHPPHP ^8.2CI passing

Since Mar 15Pushed 1mo agoCompare

[ Source](https://github.com/philiprehberger/php-csv)[ Packagist](https://packagist.org/packages/philiprehberger/php-csv)[ Docs](https://github.com/philiprehberger/php-csv)[ RSS](/packages/philiprehberger-php-csv/feed)WikiDiscussions main Synced 1mo ago

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

PHP CSV
=======

[](#php-csv)

[![Tests](https://github.com/philiprehberger/php-csv/actions/workflows/tests.yml/badge.svg)](https://github.com/philiprehberger/php-csv/actions/workflows/tests.yml)[![Latest Version on Packagist](https://camo.githubusercontent.com/a4b96e43d0c16301107b18b33f7dd1406dbd08e3eb8ecfac50fb2ea754eb6a10/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7068696c69707265686265726765722f7068702d6373762e737667)](https://packagist.org/packages/philiprehberger/php-csv)[![License](https://camo.githubusercontent.com/2cb952c7cdcb5581a817fc2ffb7cf0e1586b0f5386c4abe26937dacd5a30c8a8/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f7068696c69707265686265726765722f7068702d637376)](LICENSE)

Memory-efficient CSV reader and writer with header mapping and type casting.

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

[](#requirements)

- PHP 8.2+

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

[](#installation)

```
composer require philiprehberger/php-csv
```

Usage
-----

[](#usage)

### Reading a CSV file

[](#reading-a-csv-file)

```
use PhilipRehberger\Csv\Csv;

// Read from file with headers
$rows = Csv::read('data.csv')->toArray();
// [['name' => 'Alice', 'age' => '30'], ...]

// Read from string
$rows = Csv::readString($csvContent)->toArray();
```

### Generator-based iteration

[](#generator-based-iteration)

The reader uses PHP generators for memory-efficient processing of large files:

```
foreach (Csv::read('large-file.csv') as $row) {
    // Process one row at a time — constant memory usage
}
```

### Type casting

[](#type-casting)

Automatically detect and cast value types:

```
$rows = Csv::read('data.csv')
    ->castTypes(true)
    ->toArray();
// "42" -> int, "3.14" -> float, "true"/"false" -> bool, "" -> null
```

### Filtering and mapping

[](#filtering-and-mapping)

```
$rows = Csv::read('data.csv')
    ->castTypes(true)
    ->filter(fn (array $row) => $row['age'] >= 18)
    ->map(fn (array $row) => [...$row, 'label' => strtoupper($row['name'])])
    ->toArray();
```

### Row Validation

[](#row-validation)

Validate each row during reading. Invalid rows are skipped and errors are collected:

```
$reader = Csv::read('data.csv')
    ->validate(fn (array $row) => isset($row['email']) && str_contains($row['email'], '@'));

$rows = $reader->toArray();

// Inspect which rows failed validation
foreach ($reader->getValidationErrors() as $error) {
    echo "Row {$error['row']}: {$error['error']}\n";
}
```

The validator can also throw an exception to provide a specific error message:

```
$reader = Csv::read('data.csv')
    ->validate(function (array $row) {
        if (empty($row['name'])) {
            throw new \InvalidArgumentException('Name is required');
        }
        return true;
    });
```

### Progress Tracking

[](#progress-tracking)

Monitor processing progress with a callback invoked after each row:

```
Csv::read('large-file.csv')
    ->withProgress(function (int $rowNumber) {
        if ($rowNumber % 1000 === 0) {
            echo "Processed {$rowNumber} rows...\n";
        }
    })
    ->each(fn (array $row) => processRow($row));
```

### Custom delimiters

[](#custom-delimiters)

```
$rows = Csv::readString($tsv)
    ->delimiter("\t")
    ->toArray();
```

### Writing CSV

[](#writing-csv)

```
use PhilipRehberger\Csv\Csv;

Csv::write('output.csv')
    ->headers(['name', 'age', 'city'])
    ->row(['name' => 'Alice', 'age' => 30, 'city' => 'Berlin'])
    ->row(['name' => 'Bob', 'age' => 25, 'city' => 'Vienna'])
    ->save();

// Or get as string
$csv = Csv::write('')
    ->headers(['name', 'age'])
    ->rows($data)
    ->toString();
```

### Streaming Writer

[](#streaming-writer)

Write rows directly to disk without buffering, ideal for very large files:

```
use PhilipRehberger\Csv\Csv;

$writer = Csv::streamWrite('large-output.csv');
$writer->writeHeader(['id', 'name', 'value']);

foreach ($dataSource as $record) {
    $writer->writeRow([$record->id, $record->name, $record->value]);
}

$writer->close();
```

### BOM for Excel

[](#bom-for-excel)

Prepend a UTF-8 BOM for Excel compatibility:

```
Csv::write('output.csv')
    ->headers(['name', 'age'])
    ->rows($data)
    ->bom(true)
    ->save();
```

API
---

[](#api)

### `Csv` (static entry)

[](#csv-static-entry)

MethodDescription`Csv::read(string $path): CsvReader`Create a reader from a file path`Csv::readString(string $content): CsvReader`Create a reader from a string`Csv::write(string $path): CsvWriter`Create a writer for a file path`Csv::streamWrite(string $path, string $delimiter = ','): StreamingWriter`Create a streaming writer for a file path### `CsvReader`

[](#csvreader)

MethodDescription`delimiter(string $char): self`Set the field delimiter (default `,`)`enclosure(string $char): self`Set the field enclosure (default `"`)`hasHeader(bool $flag): self`Whether the first row is a header (default `true`)`skipEmpty(bool $flag): self`Skip empty rows (default `true`)`castTypes(bool $flag): self`Auto-detect types: int, float, bool, null`filter(callable $fn): self`Filter rows by a predicate`map(callable $fn): self`Transform each row`validate(callable $fn): self`Validate rows; invalid ones are skipped`withProgress(callable $fn): self`Set a progress callback (receives row number)`getValidationErrors(): array`Get errors from the last read`each(callable $fn): void`Execute a callback for each row`toArray(): array`Collect all rows into an array`count(): int`Count the number of rows### `CsvWriter`

[](#csvwriter)

MethodDescription`headers(array $headers): self`Set column headers`row(array $row): self`Add a single row`rows(array $rows): self`Add multiple rows`delimiter(string $char): self`Set the field delimiter (default `,`)`bom(bool $flag): self`Prepend UTF-8 BOM for Excel`save(): void`Write to the configured file path`toString(): string`Return the CSV as a string### `StreamingWriter`

[](#streamingwriter)

MethodDescription`writeHeader(array $headers): void`Write the header row`writeRow(array $row): void`Write a single data row`writeRows(array $rows): void`Write multiple data rows`isHeaderWritten(): bool`Whether the header has been written`close(): void`Close the file handleDevelopment
-----------

[](#development)

```
composer install
vendor/bin/phpunit
vendor/bin/pint --test
vendor/bin/phpstan analyse
```

License
-------

[](#license)

MIT

###  Health Score

40

—

FairBetter than 88% of packages

Maintenance90

Actively maintained with recent releases

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

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

Total

6

Last Release

50d ago

### Community

Maintainers

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

---

Top Contributors

[![philiprehberger](https://avatars.githubusercontent.com/u/8218077?v=4)](https://github.com/philiprehberger "philiprehberger (13 commits)")

---

Tags

parsergeneratorcsvwriterreadertype-casting

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/philiprehberger-php-csv/health.svg)

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

###  Alternatives

[shuchkin/simplexlsx

Parse and retrieve data from Excel XLSx files. MS Excel 2007 workbooks PHP reader.

1.8k3.8M21](/packages/shuchkin-simplexlsx)[faisalman/simple-excel-php

Easily parse / convert / write between Microsoft Excel XML / CSV / TSV / HTML / JSON / etc formats

582599.4k1](/packages/faisalman-simple-excel-php)[shuchkin/simplexlsxgen

Export data to Excel XLSx file. PHP XLSX generator.

1.1k2.2M16](/packages/shuchkin-simplexlsxgen)[csanquer/colibri-csv

Lightweight and performant CSV reader and writer library

16161.7k4](/packages/csanquer-colibri-csv)[rodenastyle/stream-parser

PHP Multiformat Streaming Parser

443195.7k2](/packages/rodenastyle-stream-parser)[akeneo-labs/spreadsheet-parser

Akeneo Spreadsheet parser. Reads XLXS files from Microsoft Excel and Open Office

147598.3k6](/packages/akeneo-labs-spreadsheet-parser)

PHPackages © 2026

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