PHPackages                             oshomo/csv-utils - 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. oshomo/csv-utils

ActiveLibrary[PDF &amp; Document Generation](/categories/documents)

oshomo/csv-utils
================

A CSV utility to read, validate and write data to multiple format including JSON, XML etc.

v6.0.1(4y ago)20121.6k↑63.3%8[1 PRs](https://github.com/hoshomoh/CSVUtils/pulls)Apache-2.0PHPPHP &gt;7.1.3CI passing

Since Sep 5Pushed 6mo ago1 watchersCompare

[ Source](https://github.com/hoshomoh/CSVUtils)[ Packagist](https://packagist.org/packages/oshomo/csv-utils)[ RSS](/packages/oshomo-csv-utils/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (8)Dependencies (2)Versions (11)Used By (0)

[![Build Status](https://camo.githubusercontent.com/667df18cf7fe2804b01b637f238ffbdf6655f1837c40120db304d3075d338425/68747470733a2f2f7472617669732d63692e636f6d2f686f73686f6d6f682f4353565574696c732e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/hoshomoh/CSVUtils)[![codecov](https://camo.githubusercontent.com/43777415ec0db1a57d76dbe52d182520ddb5af95bcfd3732f85e432debbe0a60/68747470733a2f2f636f6465636f762e696f2f67682f686f73686f6d6f682f4353565574696c732f6272616e63682f6d61737465722f67726170682f62616467652e737667)](https://codecov.io/gh/hoshomoh/CSVUtils)

CSVUtils
========

[](#csvutils)

*Make sure you use a tagged version when requiring this package.*

Table of Content
----------------

[](#table-of-content)

- [Current Stable Versions](#current-stable-versions)
- [How to Run](#how-to-run)
- [Implementation](#implementation)
- [Documentation](#documentation)
    - [Initializing a Validator](#initializing-a-validator)
    - [Validating the CSV](#validating-the-csv)
    - [Available rules](#available-rules)
    - [Writing CSV Output Data](#writing-csv-output-data)
    - [Passing Custom Rules to Validator Using Rule Object](#passing-custom-rules-to-validator-using-rule-object)
    - [Passing Custom Rules to Validator Using Closure](#passing-custom-rules-to-validator-using-closure)
    - [Writing CSV Output Data to Other Formats](#writing-csv-output-data-to-other-formats)
- [Running Tests](#running-tests)
- [Contributing to this Repo](#contributing-to-this-repo)

### Current Stable Versions

[](#current-stable-versions)

- PHP 5 [v2.0.1](https://packagist.org/packages/oshomo/csv-utils#v2.0.1)
- PHP 7 [v5.0.0](https://packagist.org/packages/oshomo/csv-utils#v5.0.0)

### How to Run

[](#how-to-run)

I have added a sample `index.php` file for a quick test of how to use the package. To run the sample; from the package root, run `composer install` then using php built in server run `php -S localhost:8000`, this would start the server at `localhost:8000`. Visit the URL from your browser and you should see the generated files in the `sample` folder at the root of the package.

### Implementation

[](#implementation)

The `Validator` expects a valid file path, the CSV delimiter, an array of validation rule(s) and an optional message(s) array to over-write the default messages of the validator.

### Documentation

[](#documentation)

##### Initializing a Validator

[](#initializing-a-validator)

Set a valid csv file path, pass the CSV delimiter and pass in your validation rules.

```
use Oshomo\CsvUtils\Validator\Validator;

$validator = new Validator(
    "some/valid/file_path",
    [
        "name" => ["ascii_only"],
        "uri"   => ["url"],
        "stars" => ["between:0,5"]
    ]
);
```

##### Validating the CSV

[](#validating-the-csv)

Now we are ready to validate the CSV. The validator provides a `validate ` method that can be called like so: `$validator->validate();`. The `validate` method returns an array of the invalid rows if validation fails. If the validation passes the `validate` method returns the CSV data as an array

A better implementation:

```
use Oshomo\CsvUtils\Validator\Validator;

$validator = new Validator(
    "some/valid/file_path",
    [
        'title' => ["ascii_only", "url"]
    ]
);

if ($validator->fails()) {
    // Do something when validation fails
    $errors = $validator->errors();
}
```

##### Error messages

[](#error-messages)

To get the rows with validation errors and their errors. The validator expose `errors` method that can be used like so `$validator->errors()`.

You can also customize the error messages for different validation rules and different attributes by passing a message array to the validator like so:

```
use Oshomo\CsvUtils\Validator\Validator;

$validator = new Validator(
    "some/valid/file_path",
    ['title' => ["ascii_only", "url"]],
    [
        'ascii_only' => 'The :value supplied for :attribute attribute is invalid on line :line of the CSV.',
        // This specifies a custom message for a given attribute.
        'hotel_link:url' => 'The :attribute must be a valid link. This error occured on line :line of the CSV.',
    ]
);
```

In this above example:

The `:attribute` place-holder will be replaced by the actual name of the field under validation. The `:value` place-holder will be replaced with value being validated. The `:line` place-holder will also be replaced with the row/line number in the CSV in which the error happened.

You may also utilize other place-holders in validation messages. For example the `between` rule exposes two other placeholder `min` and `max`. Find more about this in the available rules section

##### Available rules

[](#available-rules)

`between:min,max`:

```
Validates that a cell value is between a :min and :max. The rule exposes the :min and :max placeholder for inline messages

```

`ascii_only`:

```
Validates that a cell value does not contain a non-ascii character

```

`url`:

```
Validates that a cell value is a valid URL. By valid URL we mean

(#protocol)
(#basic auth)
(#a domain name or #an IP address or #an IPv6 address)
(#a port(optional)) then
(#a /, nothing, a / with something, a query or a fragment)

```

##### Writing CSV Output Data

[](#writing-csv-output-data)

The output of the CSV file can be written into any format. The currently suported format is `xml` and `json`. The validator exposes a `write` method to write the output data into the same folder as the CSV. Find example implementation below:

```
use Oshomo\CsvUtils\Validator\Validator;
use Oshomo\CsvUtils\Converter\JsonConverter;
use Oshomo\CsvUtils\Converter\XmlConverter;

$validator = new Validator(
    'some/valid/file_path',
    [
        "stars" => ["between:0,5"],
        "name" => ["ascii_only"],
        "uri"   => ["url"],
    ]
);

if(!$validator->fails()) {
    $validator->write(new JsonConverter());
    $validator->write(new XmlConverter("hotel"));
} else {
    print_r($validator->errors());
}
```

The `JsonConverter` simply writes the output data as JSON. The `XmlConverter` converter writes the data as XML. `XmlConverter` takes an optional parameter for setting the XML records element. If non is supplied it defaults to `item` e.g `$validator->write(new XmlConverter("hotel"));` would write the below:

```

    Beni Gold Hotel and Apartments
    5
    https://hotels.ng/hotel/86784-benigold-hotel-lagos

    Hotel Ibis Lagos Ikeja
    4
    https://hotels.ng/hotel/52497-hotel-ibis-lagos-ikeja-lagos

```

**NOTE**: *Either validation passes or fails, you can always write the CSV output data to the available formats. In cases where validation fails there would be an extra error property in the written data.*

##### Passing Custom Rules to Validator Using Rule Object

[](#passing-custom-rules-to-validator-using-rule-object)

Passing a custom rule to the validator is easy. Create a CustomRule class the implements `Oshomo\CsvUtils\Contracts\ValidationRuleInterface` interface. And pass that class to the rule array, easy. E.g:

```
use Oshomo\CsvUtils\Validator\Validator;

$validator = new Validator(
    'some/valid/file_path',
    ["name" => ["ascii_only", new UppercaseRule]]
);
```

The class definition for `UppercaseRule`. Follow the same approach if you want to create your own rule.

```
use Oshomo\CsvUtils\Contracts\ValidationRuleInterface;

class UppercaseRule implements ValidationRuleInterface
{
    /**
     * Determines if the validation rule passes. This is where we do the
     * actual validation. If the validation passes return true else false
     */
    public function passes($value, array $parameters, array $row): bool
    {
        return strtoupper($value) === $value;
    }

    /**
     * Get the validation error message. Specify the message that should
     * be returned if the validation fails. You can make use of the
     * :attribute and :value placeholders in the message string
     *
     * @return string
     */
    public function message(): string
    {
        return "The :attribute value :value must be uppercase on line :line.";
    }
}
```

If the CustomRule accepts parameters like the `between` rule, then your CustomRule class must implement both `Oshomo\CsvUtils\Contracts\ValidationRuleInterface` and `Oshomo\CsvUtils\Contracts\ParameterizedRuleInterface`. See `Oshomo\CsvUtils\Rules\Between` as an example.

##### Passing Custom Rules to Validator Using Closure

[](#passing-custom-rules-to-validator-using-closure)

If you only need the functionality of a custom rule once throughout your application, you may use a Closure instead of a rule object. The Closure receives the attribute's value, and a `$fail` callback that should be called if validation fails:

```
use Oshomo\CsvUtils\Validator\Validator;

$validator = new Validator(
    "some/valid/file_path",
    [
        "uri" => ["url", function($value, $fail) {
            if (strpos($value, "https://") !== 0) {
                return $fail('The URL passed must be https i.e it must start with https://');
            }
        }]
    ]);
```

##### Writing CSV Output Data to Other Formats

[](#writing-csv-output-data-to-other-formats)

Writing the CSV output data to other format is also very easy. Create a CustomConverter class the implements `Oshomo\CsvUtils\Contracts\ConverterHandlerInterface` interface. And pass that class to the `write` method of the validator, easy. Below is an sample implementation of a JSON converter

```
use Oshomo\CsvUtils\Contracts\ConverterHandlerInterface;

class JsonConverter implements ConverterHandlerInterface
{
    const FILE_EXTENSION = "json";

    /**
     * The converted data
     *
     * @var string
     */
    protected $data;

    /**
     * @return string
     */
    public function getExtension(): string
    {
        return JsonConverter::FILE_EXTENSION;
    }

    /**
     * @param array $data
     * @return $this|mixed
     */
    public function convert(array $data): ConverterHandlerInterface
    {
        $this->data = json_encode($data,
            JSON_PRETTY_PRINT |
            JSON_NUMERIC_CHECK |
            JSON_UNESCAPED_SLASHES |
            JSON_UNESCAPED_UNICODE
        );

        return $this;
    }

    /**
     * @param string $filename
     * @return bool
     */
    public function write(string $filename): bool
    {
        return (file_put_contents($filename, $this->data)) ? true : false;
    }
}

//////////////////////////////////////////////////////
// To use the converter above.
//////////////////////////////////////////////////////

$validator->write(new JsonConverter());
```

### Running Tests

[](#running-tests)

Run `composer test` from the root of the Package.

### Contributing to this Repo

[](#contributing-to-this-repo)

Feel free to submit a pull request for a feature or bug fix. However, do note that before your pull request can be merged it must have test written or updated as the case maybe. The project run's automatic checks to make sure that the Symfony code standards are met using [php-cs-fixer](https://symfony.com/doc/current/contributing/code/standards.html).

So, before pushing or making any pull request run the below command:

- `composer test`: For running test
- `composer fix-lint`: For running php-cs-fixer to fix linting errors

###  Health Score

46

—

FairBetter than 93% of packages

Maintenance47

Moderate activity, may be stable

Popularity43

Moderate usage in the ecosystem

Community16

Small or concentrated contributor base

Maturity64

Established project with proven stability

 Bus Factor1

Top contributor holds 87.9% 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

Every ~154 days

Recently: every ~207 days

Total

10

Last Release

1790d ago

Major Versions

v1.0.0 → v2.0.02018-05-21

v2.1.0 → v5.0.02019-03-15

v5.0.1 → v6.0.02020-03-26

PHP version history (4 changes)v1.0.0PHP ^5.6

v2.0.0PHP &gt;=5.6

v5.0.0PHP ^7.1.3

v6.0.1PHP &gt;7.1.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/4b9c6c21154ff4c544d4264bc846d8edf31a7975007a78f8183f9708cb17d894?d=identicon)[hoshomoh](/maintainers/hoshomoh)

---

Top Contributors

[![hoshomoh](https://avatars.githubusercontent.com/u/5657993?v=4)](https://github.com/hoshomoh "hoshomoh (51 commits)")[![roberto910907](https://avatars.githubusercontent.com/u/12180771?v=4)](https://github.com/roberto910907 "roberto910907 (3 commits)")[![dependabot-preview[bot]](https://avatars.githubusercontent.com/in/2141?v=4)](https://github.com/dependabot-preview[bot] "dependabot-preview[bot] (2 commits)")[![alexdawn](https://avatars.githubusercontent.com/u/12990914?v=4)](https://github.com/alexdawn "alexdawn (1 commits)")[![peter279k](https://avatars.githubusercontent.com/u/9021747?v=4)](https://github.com/peter279k "peter279k (1 commits)")

---

Tags

csvcsv-convertercsv-json-convertercsv-readingcsv-validatorcsv-xml-converterphpphplibrarycsv-validatorphp-csv-validatorcsv-convertercsv-readingcsv-json-convertercsv-xml-converter

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/oshomo-csv-utils/health.svg)

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

###  Alternatives

[mk-j/php_xlsxwriter

PHP Library to write XLSX files

1.9k8.1M27](/packages/mk-j-php-xlsxwriter)[avadim/fast-excel-writer

Lightweight and very fast XLSX Excel Spreadsheet Writer in PHP

2951.2M7](/packages/avadim-fast-excel-writer)[avadim/fast-excel-reader

Lightweight and very fast XLSX Excel Spreadsheet Reader in PHP

104608.4k6](/packages/avadim-fast-excel-reader)[avadim/fast-excel-templator

Lightweight and very fast Excel Spreadsheet generator from XLSX-templates in PHP

20106.6k](/packages/avadim-fast-excel-templator)[maksimovic/php-xlsx-writer

PHP Library to write XLSX files

1143.0k](/packages/maksimovic-php-xlsx-writer)

PHPackages © 2026

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