Skip to content

About

A lightweight PHP library for reading, searching, updating, deleting and appending records in CSV files.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

CSV Handler

PHP Version License Tests

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.

Features

  • 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.

Requirements

  • PHP 8.1 or higher.
  • PHP extensions: standard PHP filesystem and CSV functions.

Installation

clone the project

git clone https://github.com/ssegers/csv-handler.git

Include 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();

Quick start

<?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');

CSV file format

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.be

The default delimiter is a semicolon (;).

Creating an instance

$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.

Reading CSV files

readAll()

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'
    ]
]

readRows()

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.

getHeaders()

Returns the column headers.

$headers = $csv->getHeaders();

Result:

['id', 'name', 'email']

readFields()

Reads only the specified fields.

$rows = $csv->readFields([
    'id',
    'name'
]);

Result:

[
    ['id' => '1', 'name' => 'Jan'],
    ['id' => '2', 'name' => 'Piet']
]

Searching records

findRow()

Searches for the first record matching a field and value.

$user = $csv->findRow('id', '1');

if ($user !== null) {
    echo $user['name'];
}

Returns:

  • array when a matching record is found.
  • null when no matching record exists.

The comparison uses loose equality (==).

Updating records

updateRow()

Updates the first record matching the specified field and value.

$updated = $csv->updateRow(
    'id',
    '1',
    [
        'name' => 'Jan Peeters',
        'email' => 'jan.peeters@test.be'
    ]
);

Returns:

  • true when a record was updated.
  • false when no matching record was found.

Only fields defined in the CSV header can be updated.

Fields omitted from $newData retain their original values.

Deleting records

deleteRow()

Deletes the first record matching the specified field and value.

$deleted = $csv->deleteRow('id', '2');

if ($deleted) {
    echo 'Record successfully deleted.';
}

Returns:

  • true when a record was deleted.
  • false when no matching record was found.

Only the first matching record is deleted.

Appending records

appendRow()

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.

Reading records as objects

readObjectRows()

Returns records as stdClass objects using a generator.

foreach ($csv->readObjectRows() as $user) {
    echo $user->name . PHP_EOL;
}

readAsObjects()

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 files without 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;Marie

Records 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.

Custom CSV configuration

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,
    ';',
    '"',
    ''
);

Exception handling

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();
}

Testing

This project uses Pest PHP for automated testing.

Install development dependencies:

composer install

Run the test suite:

./vendor/bin/pest

Run tests with coverage:

./vendor/bin/pest --coverage

A coverage driver such as Xdebug or PCOV is required for code coverage.

Project structure

csv-handler/
│
├── src/
│   ├── CsvHandler.php
│   └── CsvException.php
│
├── tests/
│   ├── Pest.php
│   └── CsvHandlerTest.php
│
├── composer.json
├── composer.lock
├── LICENSE
└── README.md

Limitations

  • 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.

Security considerations

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.

Contributing

Contributions, bug reports and feature requests are welcome.

Please open an issue or submit a pull request on GitHub.

License

This project is licensed under the MIT License.

See the LICENSE file for details.

About

A lightweight PHP library for reading, searching, updating, deleting and appending records in CSV files.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages