PHPackages                             gbelsalvador/data-transformer - 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. [Database &amp; ORM](/categories/database)
4. /
5. gbelsalvador/data-transformer

ActiveLibrary[Database &amp; ORM](/categories/database)

gbelsalvador/data-transformer
=============================

Professional PHP library for transforming data between multiple formats

v2.0.0(3mo ago)731MITPHPPHP &gt;=8.0CI passing

Since Jan 17Pushed 3mo agoCompare

[ Source](https://github.com/Gbelsalvador/data-transformer)[ Packagist](https://packagist.org/packages/gbelsalvador/data-transformer)[ RSS](/packages/gbelsalvador-data-transformer/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (4)Versions (4)Used By (0)

Data Transformer
================

[](#data-transformer)

[![PHP Version](https://camo.githubusercontent.com/dac5fcdd705263a97f35b7c521fa27a1f7e1b7881da408d544a61864a91e6f8a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e302d3737374242342e737667)](https://www.php.net/)[![License](https://camo.githubusercontent.com/7013272bd27ece47364536a221edb554cd69683b68a46fc0ee96881174c4214c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e737667)](LICENSE)[![Tests](https://camo.githubusercontent.com/0f6aed73ee414670923e98bc24e33475e684d4e259e210987fce907495a5532e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f74657374732d504850556e69742d737563636573732e737667)](phpunit.xml.dist)[![Standards](https://camo.githubusercontent.com/19d63c70f87987521ddcf39b4dbf46d26ebb4ac54af9c7fc34b43acbdfacf2a5/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7374796c652d5053522d2d31322d627269676874677265656e2e737667)](https://www.php-fig.org/psr/psr-12/)

`gbelsalvador/data-transformer` is a PHP library for reading, transforming, validating, and exporting structured data across multiple formats.

It is designed for practical data workflows:

- import from `CSV`, `JSON`, `XML`, `SQL`, or `XLSX`
- normalize data into a consistent PHP array structure
- filter, map, and validate rows through a fluent pipeline
- export the result to another format

The project aims to offer a clean developer experience, predictable behavior, and a solid base for production-oriented data conversion workflows.

Documentation
-------------

[](#documentation)

- French README: [`README.fr.md`](README.fr.md)
- HTML documentation: [`docs/index.html`](docs/index.html)

Why This Library
----------------

[](#why-this-library)

Most conversion utilities stop at file-to-file export. Data Transformer goes further by adding a transformation pipeline between the reader and writer.

That means you can:

- convert formats
- rename and reshape fields
- filter rows
- validate data before export
- get an execution report with counts and validation errors

Features
--------

[](#features)

- Multi-format support: `CSV`, `JSON`, `XML`, `SQL`, `XLSX`
- Fluent transformation pipeline with `read()`, `filter()`, `map()`, `validate()`, `write()`
- Structured SQL filters for safer queries
- Execution reporting via `ExecutionResult`
- Spreadsheet export hardening for CSV/XLSX formula injection
- XML parsing hardened with `LIBXML_NONET`
- PHPUnit test suite for pipeline behavior and file integrations
- PSR-4 autoloading and PSR-12-friendly code style

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

[](#installation)

```
composer require gbelsalvador/data-transformer
```

Requirements
------------

[](#requirements)

- PHP `>= 8.0`
- `phpoffice/phpspreadsheet` `^5.4`

Supported Formats
-----------------

[](#supported-formats)

FormatReadWriteCSVYesYesJSONYesYesXMLYesYesSQLYesYesXLSXYesYesQuick Start
-----------

[](#quick-start)

```
use Gbelsalvador\DataTransformer\Core\Transformer;
use Gbelsalvador\DataTransformer\Readers\CsvReader;
use Gbelsalvador\DataTransformer\Writers\JsonWriter;

$transformer = new Transformer();

$result = $transformer->transform(
    new CsvReader('input.csv'),
    new JsonWriter('output.json')
);

echo $result->rowsRead();
echo $result->rowsWritten();
```

Fluent Pipeline
---------------

[](#fluent-pipeline)

The fluent API is the recommended approach for non-trivial workflows.

```
use Gbelsalvador\DataTransformer\Core\Transformer;
use Gbelsalvador\DataTransformer\Readers\CsvReader;
use Gbelsalvador\DataTransformer\Writers\JsonWriter;

$result = (new Transformer())
    ->read(new CsvReader('users.csv'))
    ->filter(fn (array $row) => ($row['active'] ?? null) === '1')
    ->map([
        'id' => 'user_id',
        'full_name' => fn (array $row) => trim(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? '')),
        'email' => 'email',
        'country' => 'country',
    ])
    ->validate([
        'id' => 'required|integer',
        'full_name' => 'required|max:120',
        'email' => 'required|email',
        'country' => 'in:FR,BE,CH,CA',
    ])
    ->write(new JsonWriter('clean-users.json'));

echo $result->rowsRead();
echo $result->rowsWritten();
echo $result->rowsInvalid();
print_r($result->validationErrors());
```

Core Concepts
-------------

[](#core-concepts)

### Readers

[](#readers)

Readers load data from a source and return a normalized PHP array:

```
[
    ['column1' => 'value1', 'column2' => 'value2'],
    ['column1' => 'value3', 'column2' => 'value4'],
]
```

Available readers:

- `CsvReader`
- `JsonReader`
- `XmlReader`
- `SqlReader`
- `XlsxReader`

### Writers

[](#writers)

Writers receive normalized rows and persist them to a target format.

Available writers:

- `CsvWriter`
- `JsonWriter`
- `XmlWriter`
- `SqlWriter`
- `XlsxWriter`

### ExecutionResult

[](#executionresult)

Every completed transformation returns an `ExecutionResult` object with runtime information:

- `rowsRead()`
- `rowsWritten()`
- `rowsFilteredOut()`
- `rowsInvalid()`
- `errorCount()`
- `duration()`
- `validationErrors()`

Usage Examples
--------------

[](#usage-examples)

### CSV to JSON

[](#csv-to-json)

```
use Gbelsalvador\DataTransformer\Core\Transformer;
use Gbelsalvador\DataTransformer\Readers\CsvReader;
use Gbelsalvador\DataTransformer\Writers\JsonWriter;

$result = (new Transformer())->transform(
    new CsvReader('products.csv', delimiter: ';'),
    new JsonWriter('products.json')
);
```

### SQL to XLSX

[](#sql-to-xlsx)

```
use Gbelsalvador\DataTransformer\Core\Transformer;
use Gbelsalvador\DataTransformer\Readers\SqlReader;
use Gbelsalvador\DataTransformer\Writers\XlsxWriter;

$pdo = new PDO('mysql:host=localhost;dbname=my_database', 'user', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$result = (new Transformer())->transform(
    new SqlReader(
        pdo: $pdo,
        tableName: 'users',
        columns: ['id', 'name', 'email', 'created_at'],
        filters: [
            'active' => 1,
            'created_at' => [
                'operator' => '>=',
                'value' => '2026-01-01',
            ],
        ]
    ),
    new XlsxWriter('active-users.xlsx', sheetName: 'Users')
);
```

### JSON to XML

[](#json-to-xml)

```
use Gbelsalvador\DataTransformer\Core\Transformer;
use Gbelsalvador\DataTransformer\Readers\JsonReader;
use Gbelsalvador\DataTransformer\Writers\XmlWriter;

$result = (new Transformer())->transform(
    new JsonReader('catalog.json'),
    new XmlWriter('catalog.xml', rootElement: 'catalog', rowElement: 'item')
);
```

Validation Rules
----------------

[](#validation-rules)

The current validation layer supports:

- `required`
- `email`
- `numeric`
- `integer`
- `boolean`
- `date`
- `max:`
- `in:value1,value2,value3`
- `same:other_field`

Example:

```
$transformer->validate([
    'email' => 'required|email',
    'status' => 'required|in:active,inactive,pending',
    'name' => 'max:120',
]);
```

SQL Safety
----------

[](#sql-safety)

`SqlReader` supports two approaches:

1. `filters`
2. `whereClause` + `whereParams`

The recommended approach is `filters`, because it builds parameterized conditions from a structured array.

```
new SqlReader(
    pdo: $pdo,
    tableName: 'users',
    filters: [
        'active' => 1,
        'role' => [
            'operator' => 'in',
            'value' => ['admin', 'editor'],
        ],
    ]
);
```

Supported structured operators:

- `=`
- `!=`
- `>`
- `>=`
- `filter(callable $callback);
$transformer->map(callable|array $mapping);
$transformer->validate(array $rules);
$result = $transformer->write(WriterInterface $writer);
```

### Reader Signatures

[](#reader-signatures)

```
new CsvReader(
    string $filePath,
    string $delimiter = ',',
    bool $hasHeader = true,
    string $enclosure = '"',
    string $escape = '\\'
);

new JsonReader(
    string $filePath,
    bool $assoc = true
);

new XmlReader(
    string $filePath,
    string $rootElement = 'root'
);

new SqlReader(
    PDO $pdo,
    string $tableName,
    array $columns = ['*'],
    ?string $whereClause = null,
    array $whereParams = [],
    array $filters = []
);

new XlsxReader(
    string $filePath,
    ?string $sheetName = null,
    bool $hasHeader = true
);
```

### Writer Signatures

[](#writer-signatures)

```
new CsvWriter(
    string $filePath,
    string $delimiter = ',',
    string $enclosure = '"',
    bool $includeHeader = true
);

new JsonWriter(
    string $filePath,
    int $flags = JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE
);

new XmlWriter(
    string $filePath,
    string $rootElement = 'root',
    string $rowElement = 'row'
);

new SqlWriter(
    PDO $pdo,
    string $tableName,
    bool $truncateFirst = false
);

new XlsxWriter(
    string $filePath,
    ?string $sheetName = null
);
```

Testing
-------

[](#testing)

Install development dependencies:

```
composer install
```

Run the test suite:

```
composer test
```

Current coverage includes:

- pipeline behavior
- validation behavior
- CSV/JSON/XML integration flows
- SQL reader/writer tests when `pdo_sqlite` is available

Note: SQL integration tests are skipped automatically if the `pdo_sqlite` driver is not enabled in your PHP environment.

Project Structure
-----------------

[](#project-structure)

```
src/
  Contracts/
  Core/
  Exceptions/
  Readers/
  Writers/

Tests/
  FileIntegrationTest.php
  SqlReadWriteTest.php
  TransformerPipelineTest.php

```

Roadmap
-------

[](#roadmap)

Planned improvements for upcoming versions:

- streaming for large datasets
- richer schema validation
- more transformation primitives
- append/merge output strategies
- additional input sources such as HTTP or YAML

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

[](#contributing)

Contributions, bug reports, and improvement ideas are welcome.

If you want to contribute:

1. Fork the repository
2. Create a feature branch
3. Add or update tests
4. Open a pull request with a clear description

License
-------

[](#license)

This project is released under the [MIT License](LICENSE).

###  Health Score

37

—

LowBetter than 81% of packages

Maintenance82

Actively maintained with recent releases

Popularity10

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity42

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

Every ~35 days

Total

3

Last Release

97d ago

Major Versions

v1.0.1 → v2.0.02026-03-29

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/154845913?v=4)[BANYI BANTU GEDEON](/maintainers/Gbelsalvador)[@Gbelsalvador](https://github.com/Gbelsalvador)

---

Top Contributors

[![Gbelsalvador](https://avatars.githubusercontent.com/u/154845913?v=4)](https://github.com/Gbelsalvador "Gbelsalvador (10 commits)")

---

Tags

data-librarylibrarylibrary-phpphp-libraryjsonxmldatasqlxlsxcsvconvertertransformer

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/gbelsalvador-data-transformer/health.svg)

```
[![Health](https://phpackages.com/badges/gbelsalvador-data-transformer/health.svg)](https://phpackages.com/packages/gbelsalvador-data-transformer)
```

###  Alternatives

[annexare/countries-list

Continents &amp; countries: ISO 3166-1 alpha-2 code, name, ISO 639-1 languages, capital, ISO 4217 currencies (symbols &amp; numeric codes), native name, phone. JSON, CSV and SQL.

1.3k253.6k1](/packages/annexare-countries-list)[faisalman/simple-excel-php

Easily parse / convert / write between Microsoft Excel XML / CSV / TSV / HTML / JSON / etc formats

578610.1k1](/packages/faisalman-simple-excel-php)[archon/dataframe

Archon: PHP Data Analysis Library

10325.1k1](/packages/archon-dataframe)[rolfvreijdenberger/izzum-statemachine

A superior statemachine library php &gt;= 5.3. Integrates with your domain models perfectly.

6426.1k](/packages/rolfvreijdenberger-izzum-statemachine)[mathielen/import-engine

Full-blown importer stack for importing almost any data into your application

2611.9k2](/packages/mathielen-import-engine)[mammothphp/woollym

WoollyM: PHP Data Analysis Library

111.6k](/packages/mammothphp-woollym)

PHPackages © 2026

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