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

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

palmtree/csv
============

CSV Reader and Writer

v4.0.1(7mo ago)26.5k↓36.9%MITPHPPHP &gt;=8.3CI failing

Since Apr 14Pushed 7mo ago1 watchersCompare

[ Source](https://github.com/palmtreephp/csv)[ Packagist](https://packagist.org/packages/palmtree/csv)[ RSS](/packages/palmtree-csv/feed)WikiDiscussions master Synced 2d ago

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

Palmtree CSV
============

[](#palmtree-csv)

[![License](https://camo.githubusercontent.com/e4babdde110513dfe42a32c52205a4b878445600fe38daa0fc2297df741ab3d7/687474703a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f70616c6d747265652f6373762e737667)](LICENSE)[![Build Status](https://camo.githubusercontent.com/284aa77ff1b54f11882ccaa008edb65f83f14d3b7debb2c8f00fc1689a4dec67/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f6275696c642f672f70616c6d747265657068702f637376)](https://scrutinizer-ci.com/g/palmtreephp/csv/build-status/master)[![Code Quality](https://camo.githubusercontent.com/7e85d4eecc982137c4c6e46f0c2027f4bc5ea13eed57c2aa36b241676fb85d20/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f7175616c6974792f672f70616c6d747265657068702f637376)](https://scrutinizer-ci.com/g/palmtreephp/csv/)[![Code Coverage](https://camo.githubusercontent.com/da19622d6a4b944e9122fe8f9dfdaac057127650a87b011a9d0c48ca26f2baa9/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f636f7665726167652f672f70616c6d747265657068702f6373762e737667)](https://scrutinizer-ci.com/g/palmtreephp/csv/code-structure/master/code-coverage)

A CSV reader and writer for PHP.

The `Reader` class implements the `Iterator` interface, loading one line into memory at a time. This means large files can be parsed without hitting any memory limits.

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

[](#requirements)

- PHP &gt;= 7.4

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

[](#installation)

Use composer to add the package to your dependencies:

```
composer require palmtree/csv
```

Usage
-----

[](#usage)

### Reading

[](#reading)

#### Reading from a CSV File

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

```
$csv = new Reader('people.csv');

foreach($csv as $row) {
    $name = $row['name'];
    if (isset($row['age'])) {
        echo "age is set!";
    }
}
```

#### Normalize Data Types

[](#normalize-data-types)

A number of different normalizers can be used to convert data from strings into certain data types. Below is contrived example using some of the currently bundled normalizers:

```
$csv = new Reader('/path/to/products.csv');

$csv->addNormalizers([
    // Convert to integer
    'product_id' => new NumberNormalizer(),

    // Keep data as string but trim it
    'name' => new StringNormalizer(),

    // Convert to float, rounded to 4 decimal places
    'price' => NumberNormalizer::create()->scale(4),

    // Convert to boolean true or false
    'enabled' => new BooleanNormalizer(),

    // Convert to an array of integers
    'related_product_ids' => new ArrayNormalizer(new NumberNormalizer()),

    // Custom conversion with a callback
    'specials' => new CallableNormalizer(fn ($value) => json_decode($value)),
]);
```

#### No Headers

[](#no-headers)

If your CSV contains no headers pass `false` as the second argument to the constructor:

```
$csv = new Reader('people.csv', false);

// Alternatively, call the setHasHeaders() method after instantiation:
//$csv->setHasHeaders(false);
```

#### Header Offset

[](#header-offset)

If your CSV headers are not on the first row you may specify the (zero based) row offset:

```
$csv = new Reader('people.csv');
// Headers are on the second row so let's set the offset to 1
$csv->setHeaderOffset(1);
```

#### Inline Reading

[](#inline-reading)

You may use the `InlineReader` to parse a CSV string rather than a file, if it was obtained from an API call or some other means:

```
$csv = new \Palmtree\Csv\InlineReader('"header_1","header_2"' . "\r\n" . '"foo","bar"');
```

### Writing

[](#writing)

#### Build and Download a CSV File

[](#build-and-download-a-csv-file)

```
$people   = [];
$people[] = [
    'name'   => 'Alice',
    'age'    => '24',
    'gender' => 'Female',
];
$people[] = [
    'name'   => 'Bob',
    'age'    => '28',
    'gender' => 'Male',
];

Downloader::download('filename.csv', $people);
```

#### Writing to a CSV File

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

```
$people   = [];
$people[] = [
    'name'   => 'Alice',
    'age'    => '24',
    'gender' => 'Female',
];
$people[] = [
    'name'   => 'Bob',
    'age'    => '28',
    'gender' => 'Male',
];

Writer::write('/path/to/output.csv', $people);
```

See the [examples](examples) directory for more usage examples.

Advanced Usage
--------------

[](#advanced-usage)

#### CSV Control

[](#csv-control)

You can access the document object to change the CSV delimiter, enclosure and escape character:

```
$csv = new Reader('/path/to/input.csv');

$csv->setDelimiter("\t");
$csv->setEnclosure('"');
$csv->setEscapeCharacter("\\");
```

#### Line Endings

[](#line-endings)

CSVs default to `\r\n` line endings. Access the document object if you need to change this:

```
$csv = new Writer('/path/to/output.csv');
$csv->getDocument()->setLineEnding("\n");
```

#### Fine-grained Control

[](#fine-grained-control)

The document object extends PHP's [SplFileObject](http://php.net/manual/en/class.splfileobject.php) and inherits its methods:

```
$csv = new Reader('/path/to/input.csv');
$csv->getDocument()->setFlags(\SplFileObject::DROP_NEW_LINE);
```

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

[](#configuration)

If you're trying to read a CSV file in or generated by an old Mac computer you may need to include the following snippet before creating a new `Reader` instance:

```
if (!ini_get('auto_detect_line_endings')) {
    ini_set('auto_detect_line_endings', '1');
}
```

This is because Macs used to use `\r` as a line separator. See [here](http://php.net/manual/en/function.fgetcsv.php#refsect1-function.fgetcsv-returnvalues) for more details.

License
-------

[](#license)

Released under the [MIT license](LICENSE)

###  Health Score

51

—

FairBetter than 95% of packages

Maintenance64

Regular maintenance activity

Popularity25

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity88

Battle-tested with a long release history

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

Recently: every ~441 days

Total

23

Last Release

217d ago

Major Versions

v0.11.5 → v1.0.02019-01-29

v1.x-dev → v2.0.02019-12-28

v2.1.1 → v3.0.02021-08-21

v3.0.1 → v4.0.02025-11-28

PHP version history (4 changes)v0.9.1PHP &gt;=5.6

v2.0.0PHP &gt;=7.1

v3.0.0PHP &gt;=7.4

v4.0.0PHP &gt;=8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/93cd57de0c03bc08173bbe424ce641b70b1bb9421f8d8fd474a33409a0f1644d?d=identicon)[palmtree](/maintainers/palmtree)

---

Top Contributors

[![andyexeter](https://avatars.githubusercontent.com/u/6660584?v=4)](https://github.com/andyexeter "andyexeter (202 commits)")

---

Tags

composer-packagecsvcsv-parsercsv-readercsv-writerphpexportcsvimportreadwrite

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Rector

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[league/csv

CSV data manipulation made easy in PHP

3.5k182.1M860](/packages/league-csv)[maatwebsite/excel

Supercharged Excel exports and imports in Laravel

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

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

1.2k70.2M244](/packages/openspout-openspout)[goodby/csv

CSV import/export library

9865.7M25](/packages/goodby-csv)[shuchkin/simplecsv

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

52100.9k](/packages/shuchkin-simplecsv)[handcraftedinthealps/goodby-csv

CSV import/export library

441.8M7](/packages/handcraftedinthealps-goodby-csv)

PHPackages © 2026

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