PHPackages                             db2file/db2file - 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. [Testing &amp; Quality](/categories/testing)
4. /
5. db2file/db2file

ActiveLibrary[Testing &amp; Quality](/categories/testing)

db2file/db2file
===============

A framework-independent PHP library for exporting MySQL database records to CSV, XLSX, DOCX and PDF.

v0.1.0(1mo ago)12↓75%MITPHPPHP ^8.1

Since Jul 16Pushed 1mo agoCompare

[ Source](https://github.com/osamasheikhdev/db2file)[ Packagist](https://packagist.org/packages/db2file/db2file)[ RSS](/packages/db2file-db2file/feed)WikiDiscussions main Synced 1w ago

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

Db2File
=======

[](#db2file)

Db2File is a framework-independent PHP library for querying MySQL data and exporting it to CSV, XLSX, DOCX, or PDF. It supports both PDO and mysqli connections, prepared query bindings, column transformations, file saving, and browser downloads.

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

[](#requirements)

- PHP 8.1 or newer
- MySQL
- PDO MySQL or mysqli
- PHP extensions required by PhpSpreadsheet, PHPWord, and Dompdf

Composer reports any missing required PHP extensions during installation.

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

[](#installation)

Install the package with Composer:

```
composer require db2file/db2file
```

Load Composer's autoloader in your application:

```
require __DIR__ . '/vendor/autoload.php';
```

Connections
-----------

[](#connections)

### PDO

[](#pdo)

```
use Db2File\Db2File;

$pdo = new PDO(
    'mysql:host=127.0.0.1;dbname=app;charset=utf8mb4',
    'root',
    'password'
);

$query = Db2File::make($pdo);
```

### mysqli

[](#mysqli)

```
use Db2File\Db2File;

$mysqli = new mysqli(
    '127.0.0.1',
    'root',
    'password',
    'app'
);

$query = Db2File::make($mysqli);
```

The procedural `mysqli_connect()` form is also supported because it returns a `mysqli` instance.

Basic Export
------------

[](#basic-export)

```
use Db2File\Db2File;

$path = Db2File::make($pdo)
    ->table('orders')
    ->select([
        'customer_name',
        'email',
        'total',
        'created_at',
    ])
    ->rename([
        'customer_name' => 'Customer',
        'total' => 'Order Total',
        'created_at' => 'Order Date',
    ])
    ->where('payment_status', '=', 'paid')
    ->currency('total', 'USD')
    ->formatDate('created_at', 'd M Y')
    ->limit(100)
    ->export()
    ->saveCsv(__DIR__ . '/exports/orders.csv');
```

Export Formats
--------------

[](#export-formats)

Save generated files to disk:

```
$export = Db2File::make($pdo)
    ->table('orders')
    ->select(['id', 'customer_name', 'total'])
    ->limit(1000)
    ->export();

$export->saveCsv(__DIR__ . '/exports/orders.csv');
$export->saveXlsx(__DIR__ . '/exports/orders.xlsx');
$export->saveDocx(__DIR__ . '/exports/orders.docx');
$export->savePdf(__DIR__ . '/exports/orders.pdf');
```

Send a file as an HTTP download:

```
Db2File::make($pdo)
    ->table('orders')
    ->select(['id', 'customer_name', 'total'])
    ->limit(1000)
    ->export()
    ->downloadXlsx('orders.xlsx');
```

Available download methods are `downloadCsv()`, `downloadXlsx()`, `downloadDocx()`, and `downloadPdf()`. CSV can also be written directly to the response with `streamCsv()`.

Download methods send HTTP headers and terminate the current request. Do not send output before calling them.

Querying
--------

[](#querying)

The fluent query builder supports:

- `where()`, `orWhere()`, and LIKE conditions
- `whereIn()`, `whereNotIn()`, and their OR variants
- `whereBetween()`, `whereNotBetween()`, and their OR variants
- `whereNull()`, `whereNotNull()`, and their OR variants
- `distinct()`, `groupBy()`, and HAVING conditions
- `count()`, `countDistinct()`, `sum()`, `avg()`, `min()`, and `max()`
- `orderBy()`, `latest()`, and `oldest()`
- `limit()`, `offset()`, and `maximumRows()`

Example:

```
$rows = Db2File::make($pdo)
    ->table('orders')
    ->select(['status'])
    ->count('id', 'Orders', 'order_count')
    ->sum('total', 'Revenue', 'revenue')
    ->whereBetween('created_at', '2026-01-01', '2026-12-31')
    ->groupBy('status')
    ->having('SUM', 'total', '>', 1000)
    ->orderBy('status')
    ->all();
```

Use `get()` for an iterable result, `all()` for an array, or `first()` for one row. `toSql()` and `bindings()` can be used to inspect the compiled query.

Transformations
---------------

[](#transformations)

Data can be transformed before it is written:

```
$export = Db2File::make($pdo)
    ->table('orders')
    ->select(['id', 'customer_name', 'email', 'status', 'total'])
    ->hide(['id'])
    ->capitalize('customer_name')
    ->lowercase('email')
    ->uppercase('status')
    ->currency('total', 'USD')
    ->addColumn(
        'summary',
        'Summary',
        static fn (array $row): string => sprintf(
            '%s: %s',
            $row['customer_name'],
            $row['status']
        )
    )
    ->limit(100)
    ->export();
```

Custom transformations are available through `transformColumn()` and `transformRow()`. Built-in helpers include `uppercase()`, `lowercase()`, `capitalize()`, `trimColumn()`, `number()`, `currency()`, `boolean()`, and `formatDate()`.

Safety
------

[](#safety)

Db2File validates table, column, and alias identifiers and binds query values through prepared statements. Always apply a suitable `limit()` or `maximumRows()` when exporting data from large tables.

Testing
-------

[](#testing)

```
composer install
composer test
```

Run only the unit test suite with:

```
composer test-unit
```

License
-------

[](#license)

Db2File is open-source software licensed under the [MIT License](LICENSE).

###  Health Score

34

—

LowBetter than 74% of packages

Maintenance90

Actively maintained with recent releases

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity32

Early-stage or recently created project

 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

Unknown

Total

1

Last Release

46d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/ef8c691599979ff13d0c01d77152ae93fa4e737a24c977f524070b36d7f1844d?d=identicon)[osamasheikh.dev](/maintainers/osamasheikh.dev)

---

Top Contributors

[![shaikh-usama](https://avatars.githubusercontent.com/u/111337320?v=4)](https://github.com/shaikh-usama "shaikh-usama (4 commits)")

---

Tags

composercsvdata-exportdatabasedocxmysqlmysqliopen-sourcepdfpdophpphp-libraryphpunitquery-builderxlsxphppdfdatabaseexportmysqlpdoxlsxcsvdocx

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/db2file-db2file/health.svg)

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

###  Alternatives

[civicrm/civicrm-core

Open source constituent relationship management for non-profits, NGOs and advocacy organizations.

769306.5k56](/packages/civicrm-civicrm-core)[maatwebsite/excel

Supercharged Excel exports and imports in Laravel

12.9k166.9M996](/packages/maatwebsite-excel)[kimai/kimai

Kimai - Time Tracking

5.0k9.7k1](/packages/kimai-kimai)[solspace/craft-freeform

The most flexible and user-friendly form building plugin!

54691.6k28](/packages/solspace-craft-freeform)[helsingborg-stad/municipio

A bootstrap theme for creating municipality sites.

4028.8k10](/packages/helsingborg-stad-municipio)[abydahana/aksara

Aksara is a modern, developer-friendly framework and CMS built on CodeIgniter 4, featuring rapid CRUD development, modular architecture, smart routing, flexible access control, API integration, and an AI assistant to make content management faster and smarter.

1141.2k](/packages/abydahana-aksara)

PHPackages © 2026

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