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

ActivePhp-ext[PDF &amp; Document Generation](/categories/documents)

csvtoolkit/fastcsv
==================

High-performance PHP extension for CSV file handling with RFC 4180 compliance

v0.0.2(10mo ago)79[1 issues](https://github.com/csvtoolkit/FastCSV-ext/issues)MITCPHP &gt;=8.2.0

Since Jun 28Pushed 10mo agoCompare

[ Source](https://github.com/csvtoolkit/FastCSV-ext)[ Packagist](https://packagist.org/packages/csvtoolkit/fastcsv)[ Docs](https://github.com/csvtoolkit/fastcsv)[ RSS](/packages/csvtoolkit-fastcsv/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)DependenciesVersions (3)Used By (0)

FastCSV PHP Extension
=====================

[](#fastcsv-php-extension)

[![License](https://camo.githubusercontent.com/7013272bd27ece47364536a221edb554cd69683b68a46fc0ee96881174c4214c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e737667)](LICENSE)[![PHP Extension](https://camo.githubusercontent.com/01c07c862cf5a0e320a1f6c951110dfe208a70c4648f72ec384c5cdf9f108324/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d457874656e73696f6e2d3737374242342e7376673f6c6f676f3d706870)](https://www.php.net/)[![RFC 4180](https://camo.githubusercontent.com/40dbd5694cda5a14128e455f33b776d0eaabe5039f7fc019cff0a8b5cf73182b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f524643253230343138302d436f6d706c69616e742d627269676874677265656e2e737667)](https://tools.ietf.org/html/rfc4180)[![Tests](https://camo.githubusercontent.com/808b128d272939ad69fce124fbff074253182d395888f5248eca40dcb2064d6c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f74657374732d3132253246313225323070617373696e672d627269676874677265656e2e737667)](tests/)[![Memory Safe](https://camo.githubusercontent.com/c54b53664e47c5ece832179944f7b8cd2b9253da2dbc2693810bea4b84d21af4/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6d656d6f72792d736166652d627269676874677265656e2e737667)](lib/)[![Performance](https://camo.githubusercontent.com/98a5ea71e185272b3f7fe211994a437238370e0c0854bf6007fdc7d42b525704/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f706572666f726d616e63652d686967682d626c75652e737667)](README.md#performance)

A high-performance PHP extension for reading and writing CSV files with full RFC 4180 compliance and advanced features.

> **Tip**: For a unified API that automatically leverages this extension when available, check out [PHP-CSVHelper](https://github.com/csvtoolkit/PHP-CSVHelper). It provides a consistent interface that uses FastCSV for maximum performance while gracefully falling back to SplFileObject when needed.

Features
--------

[](#features)

- **High Performance**: Native C implementation with optimized memory management using Arena allocation
- **RFC 4180 Compliant**: Full compliance with CSV standard including proper quote handling and multi-line records
- **Flexible API**: Support for both file paths and configuration objects in constructors
- **Configurable Flushing**: Auto-flush mode for immediate data visibility or manual flush for maximum performance
- **Advanced CSV Handling**:
    - Proper quote escaping and unescaping (`""` → `"`)
    - Multi-line quoted fields support
    - Configurable delimiters, quotes, and escape characters
    - CRLF and LF line ending support
    - Immediate or buffered write operations
- **Memory Efficient**: Arena-based memory management for optimal performance
- **Comprehensive Testing**: Extensive test suite with 100% pass rate (12/12 tests passing)

Classes
-------

[](#classes)

### FastCSVReader

[](#fastcsvreader)

High-performance CSV reader with advanced navigation capabilities.

```
// Create reader with file path
$reader = new FastCSVReader('/path/to/file.csv');

// Or with configuration object
$config = new FastCSVConfig();
$config->delimiter = ';';
$config->quote = '"';
$reader = new FastCSVReader($config);
$reader->open('/path/to/file.csv');

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

// Navigation methods
$reader->rewind();
$reader->seek(100);
$position = $reader->getPosition();
$count = $reader->getRecordCount();
$headers = $reader->getHeaders();
```

### FastCSVWriter

[](#fastcsvwriter)

High-performance CSV writer with proper quoting and escaping.

```
// Create writer with headers
$config = new FastCSVConfig();
$config->setPath('/path/to/output.csv');
$writer = new FastCSVWriter($config, ['Name', 'Age', 'City']);

// Write records (auto-flushed by default)
$writer->writeRecord(['John Doe', '30', 'New York']);
$writer->writeRecord(['Jane Smith', '25', 'Los Angeles']);

// For high-performance scenarios, disable auto-flush
$config->setAutoFlush(false);
$writer = new FastCSVWriter($config, ['ID', 'Data']);

for ($i = 0; $i < 100000; $i++) {
    $writer->writeRecord([$i, "Data$i"]);

    // Manual flush every 1000 records for optimal performance
    if ($i % 1000 == 0) {
        $writer->flush();
    }
}

$writer->close(); // Final flush on close
```

### FastCSVConfig

[](#fastcsvconfig)

Configuration class for customizing CSV parsing and writing behavior.

```
$config = new FastCSVConfig();
$config->setDelimiter(';');      // Field delimiter (default: ',')
$config->setEnclosure('"');      // Quote character (default: '"')
$config->setEscape('\\');        // Escape character (default: '\\')
$config->setHasHeader(true);     // First row contains headers (default: true)
$config->setAutoFlush(true);     // Auto-flush after each write (default: true)
$config->setStrictMode(false);   // Strict quoting mode (default: false)
$config->setSkipEmptyLines(false); // Skip empty lines (default: false)
$config->setTrimFields(false);   // Trim whitespace from fields (default: false)
$config->setWriteBOM(false);     // Write BOM for Unicode files (default: false)
```

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

[](#installation)

### Recommended: Using PIE (PHP Installer for Extensions)

[](#recommended-using-pie-php-installer-for-extensions)

The easiest way to install FastCSV is using PIE:

```
# Install the latest version
pie install csvtoolkit/fastcsv

# Install a specific version
pie install csvtoolkit/fastcsv:^0.0.1
```

For detailed PIE installation instructions, see [PIE\_INSTALLATION.md](PIE_INSTALLATION.md).

### Manual Installation

[](#manual-installation)

#### Prerequisites

[](#prerequisites)

- PHP 8.2 or higher
- GCC or compatible C compiler
- PHP development headers (`php-dev` package)

#### From Source

[](#from-source)

```
# Clone the repository
git clone
cd fastcsv-extension

# Initialize submodules (for the lib directory)
git submodule update --init --recursive

# Build the extension
phpize
./configure
make
make install
```

#### Enable Extension

[](#enable-extension)

Add to your `php.ini`:

```
extension=fastcsv
```

Or load dynamically:

```
dl('fastcsv.so'); // Linux/macOS
dl('fastcsv.dll'); // Windows
```

Development
-----------

[](#development)

### Building

[](#building)

The extension uses an external C library located in the `lib/` directory (git submodule). The build process automatically includes:

- `lib/arena.c` - Arena memory management
- `lib/csv_parser.c` - Core CSV parsing logic
- `lib/csv_reader.c` - CSV reader implementation
- `lib/csv_writer.c` - CSV writer implementation
- `lib/csv_utils.c` - Utility functions

### Testing

[](#testing)

Run the test suite:

```
# Run all tests
make test

# Run specific test
php run-tests.php tests/FastCSVReader_001.phpt

# Run with verbose output
php run-tests.php -v tests/
```

### Current Test Status

[](#current-test-status)

- **Passing**: 12/12 tests (100% success rate)
- **Comprehensive Coverage**: Edge cases, performance, memory management, and RFC 4180 compliance
- **Stable**: All tests consistently pass across different environments

Technical Details
-----------------

[](#technical-details)

### Architecture

[](#architecture)

The extension is built on top of a high-performance C library with the following components:

- **Arena Memory Management**: Efficient memory allocation and cleanup
- **Character-by-Character Parsing**: Proper handling of quoted fields and line endings
- **State Machine Parser**: RFC 4180 compliant parsing with quote state tracking
- **Configurable Parameters**: Flexible delimiter, quote, and escape character support

### Memory Management

[](#memory-management)

The extension uses Arena-based memory allocation for optimal performance:

- Each reader/writer instance maintains its own arena
- Automatic cleanup when objects are destroyed
- Minimal memory fragmentation
- Efficient bulk allocations

### RFC 4180 Compliance

[](#rfc-4180-compliance)

Full compliance with CSV standard including:

- Proper quote character handling
- Multi-line field support
- CRLF and LF line ending support
- Quote escaping (`""` becomes `"`)
- Whitespace preservation in quoted fields

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

[](#performance)

The extension is optimized for high-performance CSV processing with significant improvements over PHP's native SplFileObject:

### Benchmark Results (PHP 8.4.8, 1GB Memory Limit)

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

#### Read Operations Performance

[](#read-operations-performance)

Data SizeImplementationMedian Time (ms)Throughput (records/sec)Speed ImprovementSmall (1K rows)FastCSV3.67272,410**4.1x faster**SplFileObject15.0366,520Medium (100K rows)FastCSV176.04568,049**3.6x faster**SplFileObject639.51156,370Large (1M rows)FastCSV1,987.23503,212**4.8x faster**SplFileObject9,468.64105,612#### Combined Read/Write Operations

[](#combined-readwrite-operations)

Data SizeImplementationMedian Time (ms)Throughput (records/sec)Speed ImprovementSmall (1K rows)FastCSV22.7687,870**1.6x faster**SplFileObject35.556,341Medium (100K rows)FastCSV590.78338,535**2.5x faster**SplFileObject1,469.31136,118Large (1M rows)FastCSV7,088.8282,135**2.9x faster**SplFileObject20,513.1997,498### Key Performance Advantages

[](#key-performance-advantages)

- **Read Operations**: 3.6x to 4.8x performance improvement over SplFileObject
- **Combined Operations**: 1.6x to 2.9x advantage for read/write operations
- **Scalability**: Performance advantage increases with data size
- **Memory Efficiency**: Constant ~2MB memory usage regardless of file size
- **Consistency**: Lower standard deviation, indicating more predictable performance

### Technical Performance Features

[](#technical-performance-features)

- **Native C Implementation**: Direct memory access and optimized algorithms
- **Arena Memory Management**: Efficient bulk allocations and minimal fragmentation
- **Streaming Operations**: Constant memory usage regardless of file size
- **RFC 4180 Optimized**: Fast parsing with proper quote handling

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

[](#contributing)

See [CONTRIBUTING.md](CONTRIBUTING.md) for development guidelines.

License
-------

[](#license)

This project is licensed under the terms specified in the [LICENSE](LICENSE) file.

Changelog
---------

[](#changelog)

### Recent Updates

[](#recent-updates)

- **Arena Integration**: Updated to use Arena memory management system
- **API Improvements**: Flexible constructors accepting both strings and config objects
- **RFC 4180 Compliance**: Complete rewrite of parser for standards compliance
- **Multi-line Support**: Proper handling of quoted fields spanning multiple lines
- **Error Handling**: Improved PHP error reporting and exception handling
- **Test Coverage**: Comprehensive test suite with extensive edge case coverage

For the latest updates and bug reports, please check the project's issue tracker.

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance50

Moderate activity, may be stable

Popularity10

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity40

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

325d 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 (32 commits)")

---

Tags

phpphpextensionperformancecsvextensionrfc4180

### Embed Badge

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

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

###  Alternatives

[kartik-v/yii2-export

A library to export server/db data in various formats (e.g. excel, html, pdf, csv etc.)

1623.1M35](/packages/kartik-v-yii2-export)[keboola/csv

Keboola CSV reader and writer

1451.8M21](/packages/keboola-csv)[ajgl/csv-rfc

Drop in replacement for native PHP CSV related functions to read and/or write RFC4180 compliant CSV files

18384.7k4](/packages/ajgl-csv-rfc)[georgringer/redirect-generator

Generate redirect entries from a given set of URLs and export all to CSV

1645.5k](/packages/georgringer-redirect-generator)[phpnt/yii2-export

Yii2 It saves data in xls, csv, word, html, pdf files.

158.9k](/packages/phpnt-yii2-export)

PHPackages © 2026

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