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

ActiveLibrary

csvtoolkit/csv-helper
=====================

A PHP library for reading and writing CSV files with ease. CsvHelper supports custom delimiters, enclosures, and escape characters, providing flexible and efficient CSV data handling. It includes implementations using PHP's SplFileObject and other popular CSV libraries, ensuring compatibility with various CSV formats.

0.0.1(11mo ago)1016MITPHPPHP ^8.3.0

Since Feb 10Pushed 10mo agoCompare

[ Source](https://github.com/csvtoolkit/PHP-CSVHelper)[ Packagist](https://packagist.org/packages/csvtoolkit/csv-helper)[ RSS](/packages/csvtoolkit-csv-helper/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (9)Versions (13)Used By (0)

CSV Toolkit
===========

[](#csv-toolkit)

[![Latest Stable Version](https://camo.githubusercontent.com/56de6ab1cd06b8f45eeab983446fae3bad9f7bf1deda37e8cfbbd30947d021ab/68747470733a2f2f706f7365722e707567782e6f72672f637376746f6f6c6b69742f6373762d68656c7065722f762f737461626c65)](https://packagist.org/packages/csvtoolkit/csv-helper)[![Total Downloads](https://camo.githubusercontent.com/ad4184f1516c03b231b6c3c713c143a8184df98c1e3f951c3b9b3869cdcbfb2e/68747470733a2f2f706f7365722e707567782e6f72672f637376746f6f6c6b69742f6373762d68656c7065722f646f776e6c6f616473)](https://packagist.org/packages/csvtoolkit/csv-helper)[![License](https://camo.githubusercontent.com/4f77d056061b44201130d9d2cfc8db4a912af4846b7e9e2ac01025e5932b95ae/68747470733a2f2f706f7365722e707567782e6f72672f637376746f6f6c6b69742f6373762d68656c7065722f6c6963656e7365)](https://packagist.org/packages/csvtoolkit/csv-helper)[![PHP Version Require](https://camo.githubusercontent.com/c38599705c41f3203e174019d4a4770f05e644f9eb146888ce301dc03251c3b9/68747470733a2f2f706f7365722e707567782e6f72672f637376746f6f6c6b69742f6373762d68656c7065722f726571756972652f706870)](https://packagist.org/packages/csvtoolkit/csv-helper)

> ⚠️ **Experimental Status**: This library is currently in experimental phase. While it works correctly and passes all tests, please use with caution in production environments. We recommend thorough testing in your specific use case before deployment.

A modern, high-performance CSV processing library for PHP that automatically selects the best available implementation. CsvToolkit provides a unified interface for reading and writing CSV files, with automatic fallback between the FastCSV extension (when available) and PHP's built-in SplFileObject.

Features
--------

[](#features)

- **Automatic Implementation Selection**: Automatically uses FastCSV extension when available, falls back to SplFileObject
- **Unified Interface**: Same API regardless of underlying implementation
- **High Performance**: FastCSV extension provides significant performance improvements
- **Flexible Configuration**: Support for custom delimiters, enclosures, escape characters, and headers
- **Factory Pattern**: Simple factory methods for creating readers and writers
- **Action Classes**: Convenient action classes for quick CSV operations
- **Comprehensive Testing**: Full test suite with 146+ tests covering both implementations
- **Type Safety**: Full type declarations and PHPDoc documentation

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

[](#installation)

Install via Composer:

```
composer require csvtoolkit/csv-helper
```

### Optional: FastCSV Extension

[](#optional-fastcsv-extension)

For enhanced performance, install the FastCSV PHP extension:

```
# The library will automatically detect and use it when available
# Falls back to SplFileObject when not available
```

Quick Start
-----------

[](#quick-start)

### Using Factory (Recommended)

[](#using-factory-recommended)

```
use CsvToolkit\Factories\CsvFactory;

// Create reader (automatically selects best implementation)
$reader = CsvFactory::createReader('data.csv');

// Read all records
while (($record = $reader->nextRecord()) !== false) {
    print_r($record);
}

// Create writer
$writer = CsvFactory::createWriter('output.csv');
$writer->write(['Name', 'Age', 'Email']); // Header
$writer->write(['John Doe', '30', 'john@example.com']);
```

### Using Action Classes

[](#using-action-classes)

```
use CsvToolkit\Actions\CsvReaderAction;
use CsvToolkit\Actions\CsvWriterAction;

// Quick reader creation
$reader = CsvReaderAction::create('data.csv');

// Quick writer creation
$writer = CsvWriterAction::create('output.csv');
```

### Manual Implementation Selection

[](#manual-implementation-selection)

```
use CsvToolkit\Readers\CsvReader;      // FastCSV implementation
use CsvToolkit\Readers\SplCsvReader;   // SplFileObject implementation
use CsvToolkit\Writers\CsvWriter;      // FastCSV implementation
use CsvToolkit\Writers\SplCsvWriter;   // SplFileObject implementation
use CsvToolkit\Configs\CsvConfig;

// Configure CSV settings
$config = new CsvConfig();
$config->setDelimiter(';')
       ->setEnclosure('"')
       ->setHasHeader(true);

// Use specific implementation
$reader = new SplCsvReader('data.csv', $config);
```

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

[](#configuration)

```
use CsvToolkit\Configs\CsvConfig;

$config = new CsvConfig();
$config->setDelimiter(',')           // Field delimiter
       ->setEnclosure('"')           // Field enclosure
       ->setEscape('\\')             // Escape character
       ->setHasHeader(true);         // First row is header
```

Reading CSV Files
-----------------

[](#reading-csv-files)

```
use CsvToolkit\Factories\CsvFactory;

$reader = CsvFactory::createReader('data.csv');

// Get header (if configured)
$header = $reader->getHeader();

// Read records sequentially
while (($record = $reader->nextRecord()) !== false) {
    // Process record
}

// Or seek to specific position
$record = $reader->seek(5); // Get 6th record (0-based)

// Check if more records available
if ($reader->hasNext()) {
    $nextRecord = $reader->nextRecord();
}

// Get total record count
$totalRecords = $reader->getRecordCount();
```

Writing CSV Files
-----------------

[](#writing-csv-files)

```
use CsvToolkit\Factories\CsvFactory;

$writer = CsvFactory::createWriter('output.csv');

// Write single record
$writer->write(['John Doe', '30', 'john@example.com']);

// Write multiple records at once
$records = [
    ['Name', 'Age', 'Email'],
    ['John Doe', '30', 'john@example.com'],
    ['Jane Smith', '25', 'jane@example.com']
];
$writer->writeAll($records);
```

Implementation Detection
------------------------

[](#implementation-detection)

```
use CsvToolkit\Factories\CsvFactory;

// Check if FastCSV is available
if (CsvFactory::isFastCsvAvailable()) {
    echo "Using high-performance FastCSV extension";
} else {
    echo "Using SplFileObject fallback";
}

// Get detailed implementation info
$info = CsvFactory::getImplementationInfo();
print_r($info);
// Array
// (
//     [implementation] => FastCSV
//     [extension_loaded] => 1
//     [version] => 0.0.1
// )
```

Exception Handling
------------------

[](#exception-handling)

The library provides specific exceptions for different error conditions:

```
use CsvToolkit\Exceptions\FileNotFoundException;
use CsvToolkit\Exceptions\DirectoryNotFoundException;
use CsvToolkit\Exceptions\CsvReaderException;
use CsvToolkit\Exceptions\CsvWriterException;
use CsvToolkit\Exceptions\EmptyFileException;

try {
    $reader = CsvFactory::createReader('nonexistent.csv');
} catch (FileNotFoundException $e) {
    echo "File not found: " . $e->getMessage();
} catch (CsvReaderException $e) {
    echo "Reader error: " . $e->getMessage();
}
```

Performance
-----------

[](#performance)

When the FastCSV extension is available, CsvToolkit provides significant performance improvements over PHP's native SplFileObject:

### 🚀 Benchmark Results (PHP 8.4.8, 1GB memory limit)

[](#-benchmark-results-php-848-1gb-memory-limit)

**Read Operations:**

- **Small datasets (1K rows)**: **4.1x faster** - 272K vs 67K records/sec
- **Medium datasets (100K rows)**: **3.6x faster** - 568K vs 156K records/sec
- **Large datasets (1M rows)**: **4.8x faster** - 503K vs 106K records/sec

**Combined Read/Write Operations:**

- **Small datasets**: **1.6x faster** - 88K vs 56K records/sec
- **Medium datasets**: **2.5x faster** - 339K vs 136K records/sec
- **Large datasets**: **2.9x faster** - 282K vs 98K records/sec

### 💾 Memory Efficiency

[](#-memory-efficiency)

- **Constant memory usage**: ~2MB regardless of file size
- **Streaming operations**: No memory accumulation with large files
- **Real memory usage**: Minimal (0 bytes) due to efficient streaming

### 📊 Performance Characteristics

[](#-performance-characteristics)

- **FastCSV**: Optimized C extension with direct memory access
- **SplFileObject**: Pure PHP implementation with additional overhead
- **Scaling**: Performance advantage increases with data size
- **Consistency**: FastCSV shows lower standard deviation for predictable performance

### 🎯 Real-world Impact

[](#-real-world-impact)

- **Lower development costs**: Reduce time spent on CSV processing optimization
- **Reduce infrastructure costs**: More efficient processing means lower server resources
- **Better scalability**: Handle larger datasets without performance degradation

The library automatically selects the best available implementation without any code changes required.

**Benchmark Details**: Comprehensive performance validation available at [benchmarking-php-fastcsv](https://github.com/csvtoolkit/benchmarking-php-fastcsv)

Testing
-------

[](#testing)

Run the test suite:

```
# Test with SplFileObject (fallback)
./vendor/bin/phpunit

# Test with FastCSV extension (if available)
php -d extension=path/to/fastcsv.so ./vendor/bin/phpunit
```

Contributing
------------

[](#contributing)

We welcome contributions! Please follow these guidelines:

- Respect all modern PHP coding standards and best practices
- Ensure that all methods include type declarations
- Pass all unit tests before committing your changes
- Tests are required for any new features or bug fixes
- Maintain compatibility with both FastCSV and SplFileObject implementations

Roadmap
-------

[](#roadmap)

### Current Features ✅

[](#current-features-)

- FastCSV extension integration with automatic fallback
- Factory pattern for implementation selection
- Action classes for convenient usage
- Comprehensive exception handling
- Full type safety and documentation

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

[](#requirements)

- PHP 8.3 or higher
- Optional: FastCSV extension for enhanced performance

Support the Project
-------------------

[](#support-the-project)

If you find CSV Toolkit useful for your projects, please consider sponsoring the development! Your support helps maintain and improve this high-performance CSV library while reducing development and infrastructure costs.

[![Sponsor](https://camo.githubusercontent.com/dbafe71dd0c248a8aca4c1515ba86e972344d852759e0350b05e3ce571b56ac5/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f73706f6e736f722d2545322539442541342545462542382538462d6666363962343f7374796c653d666f722d7468652d6261646765266c6f676f3d6769746875622d73706f6e736f7273)](https://github.com/sponsors/achrafAa)

**Why sponsor?**

- 🚀 Accelerate development of new features
- 🐛 Faster bug fixes and improvements
- 📚 Better documentation and examples
- 🎯 Priority support for feature requests
- 💡 Fund research into even faster CSV processing techniques
- 💰 **Lower development costs** - Reduce your team's time spent on CSV processing optimization
- 🏗️ **Reduce infrastructure costs** - More efficient processing means lower server resources needed

License
-------

[](#license)

This project is open source and available under the MIT License. See the [LICENSE](LICENSE) file for more information.

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance52

Moderate activity, may be stable

Popularity13

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

Unknown

Total

1

Last Release

333d ago

### Community

Maintainers

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

---

Top Contributors

[![achrafAa](https://avatars.githubusercontent.com/u/36072352?v=4)](https://github.com/achrafAa "achrafAa (47 commits)")

---

Tags

composer-packagephp

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Rector

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

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

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

PHPackages © 2026

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