定制 philiprehberger/php-csv 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

philiprehberger/php-csv

Composer 安装命令:

composer require philiprehberger/php-csv

包简介

Memory-efficient CSV reader and writer with header mapping and type casting

README 文档

README

Tests Latest Version on Packagist Last updated

Memory-efficient CSV reader and writer with header mapping and type casting.

Requirements

  • PHP 8.2+

Installation

composer require philiprehberger/php-csv

Usage

Reading a CSV file

use PhilipRehberger\Csv\Csv;

// Read from file with headers
$rows = Csv::read('data.csv')->toArray();
// [['name' => 'Alice', 'age' => '30'], ...]

// Read from string
$rows = Csv::readString($csvContent)->toArray();

Generator-based iteration

The reader uses PHP generators for memory-efficient processing of large files:

foreach (Csv::read('large-file.csv') as $row) {
    // Process one row at a time — constant memory usage
}

Type casting

Automatically detect and cast value types:

$rows = Csv::read('data.csv')
    ->castTypes(true)
    ->toArray();
// "42" -> int, "3.14" -> float, "true"/"false" -> bool, "" -> null

Filtering and mapping

$rows = Csv::read('data.csv')
    ->castTypes(true)
    ->filter(fn (array $row) => $row['age'] >= 18)
    ->map(fn (array $row) => [...$row, 'label' => strtoupper($row['name'])])
    ->toArray();

Row Validation

Validate each row during reading. Invalid rows are skipped and errors are collected:

$reader = Csv::read('data.csv')
    ->validate(fn (array $row) => isset($row['email']) && str_contains($row['email'], '@'));

$rows = $reader->toArray();

// Inspect which rows failed validation
foreach ($reader->getValidationErrors() as $error) {
    echo "Row {$error['row']}: {$error['error']}\n";
}

The validator can also throw an exception to provide a specific error message:

$reader = Csv::read('data.csv')
    ->validate(function (array $row) {
        if (empty($row['name'])) {
            throw new \InvalidArgumentException('Name is required');
        }
        return true;
    });

Progress Tracking

Monitor processing progress with a callback invoked after each row:

Csv::read('large-file.csv')
    ->withProgress(function (int $rowNumber) {
        if ($rowNumber % 1000 === 0) {
            echo "Processed {$rowNumber} rows...\n";
        }
    })
    ->each(fn (array $row) => processRow($row));

First and last rows

Quickly access the first or last data row without loading everything into an array:

$first = Csv::read('data.csv')->firstRow();
// ['name' => 'Alice', 'age' => '30', ...]

$last = Csv::read('data.csv')->lastRow();
// ['name' => 'Zoe', 'age' => '28', ...]

Both methods return null if the CSV has no data rows.

Grouping rows

Group rows by a column value into an associative array:

$groups = Csv::read('data.csv')->groupBy('city');
// ['Berlin' => [['name' => 'Alice', ...], ...], 'Vienna' => [...]]

Column transformation

Apply per-column transformations during reading:

$rows = Csv::read('data.csv')
    ->transformColumn('name', fn (string $value) => strtoupper($value))
    ->transformColumn('age', fn (string $value) => (int) $value)
    ->toArray();

Duplicate detection

Find duplicate rows based on specific columns:

$duplicates = Csv::read('data.csv')->detectDuplicates(['email']);
// [2, 5] — 0-based indices of duplicate rows

Custom delimiters

$rows = Csv::readString($tsv)
    ->delimiter("\t")
    ->toArray();

TSV and PSV convenience methods

// Tab-separated values
$rows = Csv::readTsv('data.tsv')->toArray();
$tsv = Csv::writeTsv()->headers(['name', 'age'])->rows($data)->toString();

// Pipe-separated values
$rows = Csv::readPsv('data.psv')->toArray();
$psv = Csv::writePsv()->headers(['name', 'age'])->rows($data)->toString();

Writing CSV

use PhilipRehberger\Csv\Csv;

Csv::write('output.csv')
    ->headers(['name', 'age', 'city'])
    ->row(['name' => 'Alice', 'age' => 30, 'city' => 'Berlin'])
    ->row(['name' => 'Bob', 'age' => 25, 'city' => 'Vienna'])
    ->save();

// Or get as string
$csv = Csv::write('')
    ->headers(['name', 'age'])
    ->rows($data)
    ->toString();

Streaming Writer

Write rows directly to disk without buffering, ideal for very large files:

use PhilipRehberger\Csv\Csv;

$writer = Csv::streamWrite('large-output.csv');
$writer->writeHeader(['id', 'name', 'value']);

foreach ($dataSource as $record) {
    $writer->writeRow([$record->id, $record->name, $record->value]);
}

$writer->close();

Appending to an existing file

Append rows to an existing CSV without writing headers again:

Csv::write('output.csv')
    ->headers(['name', 'age'])
    ->row(['name' => 'Charlie', 'age' => 35])
    ->appendToFile('output.csv');

BOM for Excel

Prepend a UTF-8 BOM for Excel compatibility:

Csv::write('output.csv')
    ->headers(['name', 'age'])
    ->rows($data)
    ->bom(true)
    ->save();

API

Csv (static entry)

Method Description
Csv::read(string $path): CsvReader Create a reader from a file path
Csv::readString(string $content): CsvReader Create a reader from a string
Csv::readTsv(string $path): CsvReader Create a TSV reader from a file path
Csv::readPsv(string $path): CsvReader Create a PSV reader from a file path
Csv::write(string $path): CsvWriter Create a writer for a file path
Csv::writeTsv(): CsvWriter Create a TSV writer
Csv::writePsv(): CsvWriter Create a PSV writer
Csv::streamWrite(string $path, string $delimiter = ','): StreamingWriter Create a streaming writer for a file path

CsvReader

Method Description
delimiter(string $char): self Set the field delimiter (default ,)
enclosure(string $char): self Set the field enclosure (default ")
escape(string $char): self Set the field escape character (default \)
hasHeader(bool $flag): self Whether the first row is a header (default true)
skipEmpty(bool $flag): self Skip empty rows (default true)
castTypes(bool $flag): self Auto-detect types: int, float, bool, null
filter(callable $fn): self Filter rows by a predicate
map(callable $fn): self Transform each row
validate(callable $fn): self Validate rows; invalid ones are skipped
transformColumn(string $column, callable $fn): self Apply a transformer to a specific column
detectDuplicates(array $columns): array Return 0-based indices of duplicate rows
withProgress(callable $fn): self Set a progress callback (receives row number)
getValidationErrors(): array Get errors from the last read
each(callable $fn): void Execute a callback for each row
toArray(): array Collect all rows into an array
firstRow(): ?array Return the first data row or null
lastRow(): ?array Return the last data row or null
groupBy(string $column): array Group rows by a column value
count(): int Count the number of rows

CsvWriter

Method Description
headers(array $headers): self Set column headers
row(array $row): self Add a single row
rows(array $rows): self Add multiple rows
delimiter(string $char): self Set the field delimiter (default ,)
enclosure(string $char): self Set the field enclosure (default ")
escape(string $char): self Set the field escape character (default \)
bom(bool $flag): self Prepend UTF-8 BOM for Excel
appendToFile(string $path): self Append rows to an existing file (no headers)
save(): void Write to the configured file path
toString(): string Return the CSV as a string

StreamingWriter

Method Description
enclosure(string $char): self Set the field enclosure (default ")
escape(string $char): self Set the field escape character (default \)
writeHeader(array $headers): void Write the header row
writeRow(array $row): void Write a single data row
writeRows(array $rows): void Write multiple data rows
isHeaderWritten(): bool Whether the header has been written
close(): void Close the file handle

Development

composer install
vendor/bin/phpunit
vendor/bin/pint --test
vendor/bin/phpstan analyse

Support

If you find this project useful:

Star the repo

🐛 Report issues

💡 Suggest features

❤️ Sponsor development

🌐 All Open Source Projects

💻 GitHub Profile

🔗 LinkedIn Profile

License

MIT

philiprehberger/php-csv 适用场景与选型建议

philiprehberger/php-csv 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 48 次下载、GitHub Stars 达 1, 最近一次更新时间为 2026 年 03 月 15 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「generator」 「csv」 「parser」 「writer」 「reader」 「type-casting」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 philiprehberger/php-csv 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 philiprehberger/php-csv 我们能提供哪些服务?
定制开发 / 二次开发

基于 philiprehberger/php-csv 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 48
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 35
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-03-15