A lightweight PHP library for reading, searching, updating, deleting and appending records in CSV files.
CSV Handler provides a simple and convenient object-oriented interface for working with CSV files without requiring a database.
No Composer required. Simply download the library and include the provided autoload.php file.
- Read CSV files with or without headers.
- Configurable delimiter, enclosure and escape characters.
- Read records as associative or numeric arrays.
- Read CSV records using generators.
- Retrieve selected fields.
- Search records by field value.
- Update existing records.
- Delete existing records.
- Append new records.
- Convert CSV records into stdClass objects.
- Memory-efficient row-by-row processing.
- Automatic validation of CSV structure.
- Temporary-file handling for update and delete operations.
- PHP 8.1 or higher.
- PHP extensions: standard PHP filesystem and CSV functions.
clone the project
git clone https://github.com/ssegers/csv-handler.gitInclude the required PHP files in your project: Include the autoloader in your PHP project:
require_once '/path/to/csv-handler/autoload.php';You can now use the CSV Handler:
use SeDaSoft\Csv\CsvHandler;
$csv = new CsvHandler('users.csv');
$users = $csv->readAll();<?php
require_once __DIR__ . '/libraries/csv-handler/autoload.php';
use SeDaSoft\Csv\CsvHandler;
$csv = new CsvHandler('users.csv');
// Read all records
$users = $csv->readAll();
// Find a user
$user = $csv->findRow('id', '1');
// Append a new user
$csv->appendRow([
'id' => 3,
'name' => 'Piet',
'email' => 'piet@test.be'
]);
// Update a user
$csv->updateRow('id', '1', [
'name' => 'Jan Peeters'
]);
// Delete a user
$csv->deleteRow('id', '3');By default, CSV Handler expects a CSV file with headers.
Example users.csv:
id;name;email
1;Jan;jan@test.be
2;Piet;piet@test.beThe default delimiter is a semicolon (;).
$csv = new CsvHandler(
'users.csv',
true,
';',
'"',
'\\'
);Constructor parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
$filePath |
string | Required | Path to the CSV file |
$hasHeader |
bool | true | Indicates whether the CSV contains headers |
$delimiter |
string | ; |
Field delimiter |
$enclosure |
string | " |
Field enclosure |
$escape |
string | \ |
Escape character |
All delimiter and enclosure characters must be exactly one byte. The escape character can also be an empty string.
Reads all records and returns them as an array.
$rows = $csv->readAll();
print_r($rows);Result:
[
[
'id' => '1',
'name' => 'Jan',
'email' => 'jan@test.be'
],
[
'id' => '2',
'name' => 'Piet',
'email' => 'piet@test.be'
]
]Reads records using a generator.
foreach ($csv->readRows() as $row) {
echo $row['name'] . PHP_EOL;
}This method is useful when processing large CSV files because records are processed one at a time.
Returns the column headers.
$headers = $csv->getHeaders();Result:
['id', 'name', 'email']Reads only the specified fields.
$rows = $csv->readFields([
'id',
'name'
]);Result:
[
['id' => '1', 'name' => 'Jan'],
['id' => '2', 'name' => 'Piet']
]Searches for the first record matching a field and value.
$user = $csv->findRow('id', '1');
if ($user !== null) {
echo $user['name'];
}Returns:
arraywhen a matching record is found.nullwhen no matching record exists.
The comparison uses loose equality (==).
Updates the first record matching the specified field and value.
$updated = $csv->updateRow(
'id',
'1',
[
'name' => 'Jan Peeters',
'email' => 'jan.peeters@test.be'
]
);Returns:
truewhen a record was updated.falsewhen no matching record was found.
Only fields defined in the CSV header can be updated.
Fields omitted from $newData retain their original values.
Deletes the first record matching the specified field and value.
$deleted = $csv->deleteRow('id', '2');
if ($deleted) {
echo 'Record successfully deleted.';
}Returns:
truewhen a record was deleted.falsewhen no matching record was found.
Only the first matching record is deleted.
Appends a new record to the CSV file.
$csv->appendRow([
'id' => 3,
'name' => 'Marie',
'email' => 'marie@test.be'
]);The fields are automatically reordered according to the CSV headers.
Missing fields are automatically filled with empty values.
Unknown fields cause an InvalidArgumentException.
Returns records as stdClass objects using a generator.
foreach ($csv->readObjectRows() as $user) {
echo $user->name . PHP_EOL;
}Reads all records and returns an array of stdClass objects.
$users = $csv->readAsObjects();
foreach ($users as $user) {
echo $user->name . PHP_EOL;
}Both methods require a CSV file with headers.
CSV Handler also supports files without headers.
Create an instance with $hasHeader set to false:
$csv = new CsvHandler(
'data.csv',
false
);Example CSV:
1;Jan
2;Piet
3;MarieRecords are returned as numeric arrays:
$rows = $csv->readAll();Result:
[
['1', 'Jan'],
['2', 'Piet'],
['3', 'Marie']
]Appending records is also supported:
$csv->appendRow([
'4',
'Peter'
]);Searching, updating and deleting by field name require headers and are therefore not supported without headers.
CSV Handler supports custom delimiters and enclosure characters.
For example, a comma-separated CSV file:
$csv = new CsvHandler(
'users.csv',
true,
','
);A CSV file using single quotes as enclosure:
$csv = new CsvHandler(
'users.csv',
true,
';',
"'"
);You can also disable the escape character:
$csv = new CsvHandler(
'users.csv',
true,
';',
'"',
''
);CSV Handler throws exceptions when operations fail.
Common exceptions include:
| Exception | Description |
|---|---|
RuntimeException |
File access or read/write errors |
InvalidArgumentException |
Invalid parameters or unknown fields |
LogicException |
Operation not supported for the current CSV configuration |
CsvException |
Invalid CSV structure |
Example:
try {
$csv = new CsvHandler('users.csv');
$user = $csv->findRow('id', '1');
} catch (CsvException $e) {
echo 'Invalid CSV structure: ' . $e->getMessage();
} catch (RuntimeException $e) {
echo 'File error: ' . $e->getMessage();
} catch (InvalidArgumentException $e) {
echo 'Invalid argument: ' . $e->getMessage();
} catch (LogicException $e) {
echo 'Operation not supported: ' . $e->getMessage();
}This project uses Pest PHP for automated testing.
Install development dependencies:
composer installRun the test suite:
./vendor/bin/pestRun tests with coverage:
./vendor/bin/pest --coverageA coverage driver such as Xdebug or PCOV is required for code coverage.
csv-handler/
│
├── src/
│ ├── CsvHandler.php
│ └── CsvException.php
│
├── tests/
│ ├── Pest.php
│ └── CsvHandlerTest.php
│
├── composer.json
├── composer.lock
├── LICENSE
└── README.md
- CSV Handler is designed for local CSV files.
- CSV fields are returned as strings.
- Searching, updating and deleting require headers.
- Update and delete operations rewrite the CSV file.
- Concurrent write operations are not automatically protected by file locking.
- CSV files are not a replacement for a relational database.
CSV Handler does not automatically sanitize values for spreadsheet applications.
If CSV data is opened in Excel or similar spreadsheet software, be aware of CSV formula injection. Untrusted values beginning with characters such as =, +, - or @ may be interpreted as formulas.
Applications should validate or sanitize untrusted data according to their requirements.
Contributions, bug reports and feature requests are welcome.
Please open an issue or submit a pull request on GitHub.
This project is licensed under the MIT License.
See the LICENSE file for details.