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

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

godsgood33/csv-reader
=====================

This library simplifies reading CSV files

2.1(2y ago)120Apache-2.0PHPPHP &gt;=7.4

Since Oct 11Pushed 2y ago2 watchersCompare

[ Source](https://github.com/godsgood33/csv-reader)[ Packagist](https://packagist.org/packages/godsgood33/csv-reader)[ RSS](/packages/godsgood33-csv-reader/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (10)Dependencies (3)Versions (15)Used By (0)

CSV Reader
==========

[](#csv-reader)

Intro
-----

[](#intro)

The purpose of this library is to simplify reading and parsing CSV files. I have parsed CSV files so many times and there is not really an easy way to do it. You have to know the index of the column you want to insert and it would be so much more readable if you could just use the header title itself as the field index. A while ago, I started reading the header row, flipping the array so that the index of the row elements is now the value of the field index.

```
$header = array_flip(fgetcsv($fh));
/*
 array(
     'column1' => 0,
     'column2' => 1,
     'column3' => 2,
     ...
 )
 */
```

This allows you the ability to use the header title as an index into the data array.

```
foreach($data = fgetcsv($fh)) {
  // $data is now a numeric indexed array
  // $header['column1'] will return 0 so $data[$header['column1']] will return the value of the first index in the array to the CSV
  $column1 = $data[$header['column1']];
}
```

This is nice, but isn't any more readable than just using the index itself (or store the index in a variable and using that)...

```
$column1 = $data[$column1HeaderIndex];
```

So what I thought I would do is create a library that would allow you to use the header titles as field names. Here's how you do it.

Installation/Setup
------------------

[](#installationsetup)

```
composer require godsgood33/csv-reader

```

Dev.to
------

[](#devto)

I have done a more thorough explanation on Dev.to

- [CSV-Reader](https://dev.to/godsgood33/csv-parsing-library-3n8o)
- [Filter &amp; Maps](https://dev.to/godsgood33/csv-reader-filters-and-maps-43ld)
- [Links](https://dev.to/godsgood33/csv-parser-links-4mk6)

Use
---

[](#use)

Pass your CSV filename into the class and create an object

```
$reader = new Reader($csvFilename);
```

### **Options**

[](#options)

These options are available as an associative array as the second parameter of the constructor

- delimiter - **,** (default)
    - what character separates the fields
- enclosure - **"** (default)
    - what character surrounds a field should it contain the delimiter character
- escape - **\\** (default)
    - what character will escape an enclosure character
- header - 0 (default)
    - what row (0-based) is the header title row on
- alias - **\[\]**
    - an array of aliases and what field they point to
        - \[ 'name' =&gt; 'Name', 'phone' =&gt; 'PhoneNumber', 'email' =&gt; 'Email' \]
- required\_headers - **\[\]**
    - what headers are required to be present in the file *(formatted the way they would be after invalid character removal or converting to lower case)*
        - \['Name', 'PhoneNumber', 'Email'\]
- headerCase - **int**
    - an integer defining if you want to change the case of the header fields
        - `Header::TO_LOWER` - set all characters to lower case (e.g. 'phonenumber')
        - `Header::TO_CAMEL_CASE` - sets the first character to lower case and all other words first character to upper case (e.g. 'phoneNumber')

```
// sets the column delimiter to the semi-colon, the header column is now the second row and changes the header properties to all the lower case
$reader = new Reader($csvFilename, [
    'delimiter' => ';',
    'enclosure' => "'",
    'header' => 1,
    'headerCase' => Header::TO_LOWER,
]);
```

The Reader will remove any non-alphanumeric characters `[^a-zA-Z0-9_]`.

After this is done, all you need to do is start looping until the end of the file is reached or the data you're looking for is found.

NOTE: Reader will automatically read the first row after the header after it is done parsing so **DON'T use a `while` loop**

Inside your loop you can use the header titles as field names to retrieve the data at each column

```
do {
    $name = $reader->name;
    $phone = $reader->phone;
    $email = $reader->email;
} while($reader->next());
```

Required Headers
----------------

[](#required-headers)

If there are required headers that you must have in your file you can specify them in the 'required\_headers' option passed in at instantiation time.

```
// this will first check that the 'name', 'phone', and 'email' columns are present before proceeding...throws a "InvalidHeaderOrField" exception is something is missing
$reader = new Reader('file.csv', ['required_headers' => [
    'name', 'phone', 'email'
]]);
```

Aliases
-------

[](#aliases)

If you would like to specify that a field has an alias name you can specify that with the `'alias'` associative array option. The key parameter is the alias and the value is the field it points to.

```
$reader = new Reader('file.csv', [
  'alias' => [
      'digits' => 'phone',
      'zip' => 'postalcode'
    ]
  ]
);
```

The above would allow you to use the either of the following:

```
$phone = $reader->digits;
$phone = $reader->phone;
```

Maps
----

[](#maps)

[Full Explanation](./docs/MAPS.md)

Maps in `CSVReader` are a way that you can read multiple fields at once and return all of them in a formatted string.

Filters
-------

[](#filters)

[Full Explanation](./docs/FILTERS.md)

Filters can be a really powerful option when parsing a file. They can be used to validate the field values before ingesting them into the system, for manipulating the data, removing or adding characters, adding in other data so that it works better in a database or HTML, or creating an object from a field value. Filters can be used along with aliases, but you **MUST** do the filter on the field that is in the file...**not** the alias. In the example above, the filter would have to be assigned to the `phone` field and not `digits`. Filters do **NOT** work with Maps as those already include their own callback so the filter functionality can be accomplished in the `Map` callback.

Links
-----

[](#links)

[Full Explanation](./docs/LINKS.md)

Links are a way that you can retrieve multiple fields at the same time and return them as a `stdClass` object or create your own object.

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity8

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity62

Established project with proven stability

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

Recently: every ~133 days

Total

14

Last Release

1039d ago

Major Versions

0.3 → 1.02021-01-07

v1.4.x-dev → 2.02022-11-08

PHP version history (2 changes)v1.3.x-devPHP ^7.4

1.3.1PHP &gt;=7.4

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/80628?v=4)[ryanp](/maintainers/ryanp)[@ryanp](https://github.com/ryanp)

---

Top Contributors

[![godsgood33](https://avatars.githubusercontent.com/u/1922710?v=4)](https://github.com/godsgood33 "godsgood33 (74 commits)")

---

Tags

csvparsed-csv-files

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[spatie/browsershot

Convert a webpage to an image or pdf using headless Chrome

5.2k32.1M102](/packages/spatie-browsershot)[barryvdh/laravel-snappy

Snappy PDF/Image for Laravel

2.8k24.8M48](/packages/barryvdh-laravel-snappy)[openspout/openspout

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

1.2k57.6M131](/packages/openspout-openspout)[keboola/csv

Keboola CSV reader and writer

1451.8M21](/packages/keboola-csv)[setasign/tfpdf

This class is a modified version of FPDF that adds UTF-8 support. The latest version is based on FPDF 1.85.

426.1M30](/packages/setasign-tfpdf)[aspera/xlsx-reader

Spreadsheet reader library for XLSX files

52742.2k5](/packages/aspera-xlsx-reader)

PHPackages © 2026

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