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

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

pmg/csv-sugar
=============

Little bit of sugar for reading and writing CSV files.

v2.1.0(3y ago)063.6kMITPHPPHP ^8.0

Since Jan 7Pushed 2y ago11 watchersCompare

[ Source](https://github.com/AgencyPMG/CsvSugar)[ Packagist](https://packagist.org/packages/pmg/csv-sugar)[ RSS](/packages/pmg-csv-sugar/feed)WikiDiscussions master Synced 2mo ago

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

CSV Sugar
=========

[](#csv-sugar)

[![Build Status](https://camo.githubusercontent.com/c30004bc196eb1f22d14c38b3b534d1d1280f483f78c5135856bb5d1c8be3517/68747470733a2f2f7472617669732d63692e6f72672f4167656e6379504d472f43737653756761722e737667)](https://travis-ci.org/AgencyPMG/CsvSugar)

⚠️ **DEPRECATION NOTICE**: This project is no longer maintained and might not work as expected. Use [Alli Platform SDK for PHP](https://github.com/AgencyPMG/alli-platform-sdk-php/tree/master/src/Util/Csv) instead. Check this migration guide for more information: [Migrating from PMG CsvSugar to Alli Platform SDK for PHP](https://agencypmg.atlassian.net/wiki/spaces/ALLISDK/pages/2996862986/Alli+Platform+SDK+0.36+Upgrade+Guide)

---

A few helpers to make reading and writing CSV (and other delimited files) a bit easier.

Reading CSV
-----------

[](#reading-csv)

```
use PMG\CsvSugar\SimpleReader;
use PMG\CsvSugar\DictReader;

// pretty close to simply using SplFileObject
$reader = new SimpleReader('/path/to/file.csv');
foreach ($reader as $row) {
  // do stuff with $row
}

// Reading a CSV file into associative arrays with the first row of the file
// as the keys
$reader = new DictReader('/path/to/file.csv');
foreach ($reader as $row) {
  // $row['some_column'], etc
}

// Or you can tell DictReader some more about what you want to do
$reader = DictReader::builder('/path/to/file.csv')
  ->withFields(['one', 'two', 'three']) // the column names
  ->withRestKey('_extra_columns') // where to put the stuff from rows that are too long
  ->withRestValue('missing') // the value to put in on rows that are too short
  ->build();

/* the above is the same as...
$reader = new DictReader(
  '/path/to/file.csv',
  null, // dialect, see below
  ['one', 'two', 'three'], // fields
  '_extra_columns', // rest key
  'missing', // rest value
)
*/

foreach ($reader as $row) {
  // use $row['one'], etc
}
```

Writing CSV
-----------

[](#writing-csv)

```
use PMG\CsvSugar\SimpleWriter;
use PMG\CsvSugar\DictWriter;

// pretty close to plain old SplFileObject
$writer = new SimpleWriter('/path/to/file.csv');
// write a single row
$writer->writeRow(['one', 'two', 'three']);
// or write multiple rows, useful if you have an iterator to pass in here
$writer->writeRows([
    ['three', 'for', 'five'],
]);

// writeRow(s) can also take anything that implements `Traverable`
function makeRows() {
  foreach (range(0, 10) as $_) {
    yield new \ArrayIterator(range(1, 4));
  }
}

$writer->writeRow(new \ArrayIterator(['one', 'two', 'three']));
$writer->writeRows(makeRows());

// or use a dict writer to only output certain fields.

$writer = new DictWriter(
    '/path/to/file.csv',
    null, // dialect, see below
    ['one', 'two', 'three']
);
$writer->writeHeader(); // output the column names
$writer->writeRow([
    'one' => 1,
    'two' => 2,
    'three' => 3,
    'four' => 4, // ignored by default
]);

$writer->writeRows([
    [
        'one' => 1,
        'two' => 2,
        'three' => 3,
        'four' => 4, // ignored by default
    ],
]);

// want to be strict about it? Tell the writer to error when invalid
// keys are present
$writer = new DictWriter(
    '/path/to/file.csv',
    null, // dialect, see below
    ['one', 'two', 'three'],
    DictWriter::ERROR_INVALID
);
$writer->writeRow([
    'four' => 4, // will throw an exception
]);

// you can also tell `DictWriter` what you want to use when fields are missing
// we'll use a builder here since the constructor is getting a big unwieldy
$writer = DictWriter::builder('/path/to/file.csv')
    ->withFields(['one', 'two', 'three']) // fields to be output
    ->withExtraBehavior(DictWriter::ERROR_INVALID) // throw on invalid fields
    // default: ->withExtraBehavior(DictWriter::IGNORE_INVALID)
    ->withRestValue('missing') // defaults to an empty string
    ->build();

// 'two' and 'three' will be get filled in with 'missing'
$writer->writeRow([
    'one' => 1,
]);
```

Dialects
--------

[](#dialects)

A `Dialect` is a small value object representing how the CSV is written -- what the delimiter, enclsoure, and escape character is. The default dialect is CSV and all readers and writer take an (optional) `Dialect` objects as their second constructor argument.

### Custom Dialects

[](#custom-dialects)

```
use PMG\CsvSugar\Dialect;

// $delimiter, $enclosure, $escapeCharacter
$dialect = new Dialect(',', "'", '\\');
```

### Named Constructors

[](#named-constructors)

```
use PMG\CsvSugar\Dialect;

$csv = Dialect::csv();
$tabSeparated = Dialect::tsv();
$pipeSeparated = Dialect::pipe();
$tildeSeparated = Dialect::tilde();
```

###  Health Score

35

—

LowBetter than 79% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity22

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity71

Established project with proven stability

 Bus Factor1

Top contributor holds 92.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 ~854 days

Total

4

Last Release

1219d ago

Major Versions

1.0.0 → 2.0.02018-04-05

PHP version history (4 changes)1.0.0PHP &gt;=5.6

2.0.0PHP ~7.1

v2.0.1PHP ^7.4 || ^8.0

v2.1.0PHP ^8.0

### Community

Maintainers

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

---

Top Contributors

[![chrisguitarguy](https://avatars.githubusercontent.com/u/1010392?v=4)](https://github.com/chrisguitarguy "chrisguitarguy (36 commits)")[![WebCu](https://avatars.githubusercontent.com/u/3429093?v=4)](https://github.com/WebCu "WebCu (3 commits)")

---

Tags

csv

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  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)[goodby/csv

CSV import/export library

9555.6M23](/packages/goodby-csv)[sonata-project/exporter

Lightweight Exporter library

44920.9M35](/packages/sonata-project-exporter)

PHPackages © 2026

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