Skip to content
Merged

Guides #2750

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,4 @@ jobs:
uses: "docker://norberttech/md-link-linter@sha256:bf17e53dd716dcc2f0a41ed45af3e7bfc06b56b40fe6d8064b29646c1582c54c" # latest as of 2026-09-25
with:
entrypoint: "/composer/vendor/bin/mdlinklint"
args: "--exclude=vendor --exclude=tests --exclude=examples --exclude=documentation ."
args: "--exclude=vendor --exclude=tests --exclude=examples --exclude=guides --exclude=documentation ."
1 change: 1 addition & 0 deletions web/landing/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ var/
public/assets
public/images/blog/social/
public/images/work-shop/social/
public/images/guides/social/
public/pagefind
public/*.xml
!public/BingSiteAuth.xml
Expand Down
49 changes: 49 additions & 0 deletions web/landing/assets/controllers/code_tabs_controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { Controller } from '@hotwired/stimulus';

const STORAGE_KEY = 'code-tab';
const CHANGE_EVENT = 'code-tabs:change';

export default class extends Controller {
static targets = ['tab', 'panel'];

#onChange = null;

connect() {
this.#onChange = (event) => this.#show(event.detail.name);
document.addEventListener(CHANGE_EVENT, this.#onChange);

this.element.classList.add('code-tabs-ready');
this.#show(this.#stored());
}

disconnect() {
document.removeEventListener(CHANGE_EVENT, this.#onChange);
}

select({ params: { name } }) {
try {
localStorage.setItem(STORAGE_KEY, name);
} catch (error) {
// storage can be blocked, the choice then lasts for this page only
}

document.dispatchEvent(new CustomEvent(CHANGE_EVENT, { detail: { name } }));
}

#show(name) {
const names = this.panelTargets.map((panel) => panel.dataset.tab);
const selected = this.tabTargets.find((tab) => tab.getAttribute('aria-selected') === 'true');
const active = names.includes(name) ? name : (selected?.dataset.codeTabsNameParam ?? names[0]);

this.tabTargets.forEach((tab) => tab.setAttribute('aria-selected', String(tab.dataset.codeTabsNameParam === active)));
this.panelTargets.forEach((panel) => { panel.hidden = panel.dataset.tab !== active; });
}

#stored() {
try {
return localStorage.getItem(STORAGE_KEY);
} catch (error) {
return null;
}
}
}
23 changes: 23 additions & 0 deletions web/landing/assets/styles/app.css
Original file line number Diff line number Diff line change
Expand Up @@ -891,6 +891,29 @@ code {
}
}

.code-tabs-list {
@apply flex flex-wrap gap-1 mt-5 -mb-3;
}

.code-tab {
@apply rounded-md border border-slate-200 bg-white px-3 py-1.5 text-sm font-medium text-slate-600
transition-colors hover:text-slate-900
dark:border-white/10 dark:bg-white/[0.03] dark:text-white/70 dark:hover:text-white;
}

.code-tab[aria-selected="true"] {
@apply border-blue-300 text-slate-900 dark:border-blue-100 dark:text-white;
}

.code-tabs-label {
@apply mt-5 -mb-3 text-xs font-semibold uppercase tracking-[0.18em] text-slate-500 dark:text-white/55;
}

.code-tabs:not(.code-tabs-ready) .code-tabs-list,
.code-tabs-ready .code-tabs-label {
display: none;
}

#site-search {
--pf-text: #0f172a;
--pf-text-secondary: #475569;
Expand Down
9 changes: 9 additions & 0 deletions web/landing/config/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ services:
arguments:
$publicDir: '%kernel.project_dir%/public'

Flow\Website\SocialCard\Guides\CardGenerator:
arguments:
$publicDir: '%kernel.project_dir%/public'

Flow\Website\StaticSourceProvider\:
resource: '../src/Flow/Website/StaticSourceProvider/'
tags: ['static_content_generator.source_provider']
Expand All @@ -78,6 +82,11 @@ services:
arguments:
$basePath: '%documentation_base_path%'

guides.pages:
class: Flow\Website\Service\Documentation\Pages
arguments:
$basePath: '%kernel.project_dir%/content/guides'

Flow\Website\Twig\:
resource: '../src/Flow/Website/Twig/**/*Extension.php'
tags: [twig.extension]
Expand Down
177 changes: 177 additions & 0 deletions web/landing/content/guides/export-database-to-excel-in-php.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
---
seo_title: 'PhpSpreadsheet out of memory: export a database table to Excel in PHP'
seo_description: 'PhpSpreadsheet keeps the whole workbook in memory, so a big export ends with "Allowed memory size exhausted". Why it happens, and how to export a million rows to XLSX in 28Mb.'
group: Writing files
problem: 'PhpSpreadsheet runs out of memory'
proof_label: 'A million orders to XLSX'
proof_before: '3663Mb'
proof_after: '28Mb'
published: '2026-11-18'
updated: '2026-11-18'
---

# Export a database table to Excel in PHP without running out of memory

Let's say somebody from finance asks for all our orders as an Excel file.
There are a million of them in the database, and our PHP process runs with the default `memory_limit` of 128Mb.

> The scripts in this guide need a database and PhpSpreadsheet, so they don't run in the playground. Run them on your machine.

## The database

We need a table with orders, so let's create one. It's a SQLite file, so there is no server to set up.

```php ignore
<?php

declare(strict_types=1);

$rows = 1_000_000;
$database = new PDO('sqlite:' . __DIR__ . '/orders.sqlite');

$database->exec('DROP TABLE IF EXISTS orders');
$database->exec('CREATE TABLE orders (id INTEGER PRIMARY KEY, email TEXT, country TEXT, amount REAL, created_at TEXT)');

$insert = $database->prepare('INSERT INTO orders VALUES (?, ?, ?, ?, ?)');
$database->beginTransaction();

for ($id = 1; $id <= $rows; $id++) {
$insert->execute([
$id,
"customer{$id}@example.com",
['PL', 'US', 'DE', 'FR', 'GB'][$id % 5],
($id % 1000) / 10,
gmdate('Y-m-d H:i:s', 1_700_000_000 + $id * 60),
]);
}

$database->commit();

echo "orders.sqlite: {$rows} rows\n";
```

```text
orders.sqlite: 1000000 rows
```

## Export to Excel with PhpSpreadsheet

The first thing that comes to mind is PhpSpreadsheet.
We don't load the whole table. We fetch the orders one by one and add every order to the sheet.

```bash
composer require phpoffice/phpspreadsheet
```

```php ignore
<?php

declare(strict_types=1);

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

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

$database = new PDO('sqlite:' . __DIR__ . '/orders.sqlite');
$orders = $database->query('SELECT id, email, country, amount, created_at FROM orders ORDER BY id');

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray(['id', 'email', 'country', 'amount', 'created_at'], null, 'A1');
$line = 2;

while ($order = $orders->fetch(PDO::FETCH_NUM)) {
$sheet->fromArray($order, null, 'A' . $line++);
}

(new Xlsx($spreadsheet))->save(__DIR__ . '/orders.xlsx');
```

With a hundred thousand orders it works, it just needs 367Mb to do it. With a million orders it ends like this:

```text
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 4096 bytes)
```

## Why PhpSpreadsheet ends with "Allowed memory size exhausted"

We fetch the orders one by one, so where does the memory go?

It goes to the output. PhpSpreadsheet keeps every cell of the workbook in memory until we call `save()`, so every order we add costs us more memory.
We could raise `memory_limit`, but for our million orders that means 3663Mb and more than a minute and a half of waiting.

## The same export with Flow

Flow needs PHP 8.3 or newer.

```bash
composer require flow-php/etl flow-php/etl-adapter-doctrine flow-php/etl-adapter-excel
```

```php ignore
<?php

declare(strict_types=1);

use function Flow\ETL\Adapter\Doctrine\{from_dbal_key_set_qb, pagination_key_asc, pagination_key_set};
use function Flow\ETL\Adapter\Excel\DSL\{from_excel, to_excel};
use function Flow\ETL\DSL\{data_frame, overwrite, to_output};
use Doctrine\DBAL\DriverManager;

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

$database = DriverManager::getConnection(['driver' => 'pdo_sqlite', 'path' => __DIR__ . '/orders.sqlite']);

data_frame()
->read(from_dbal_key_set_qb(
$database,
$database->createQueryBuilder()->select('id', 'email', 'country', 'amount', 'created_at')->from('orders'),
pagination_key_set(pagination_key_asc('id')),
))
->write(to_excel(__DIR__ . '/orders.xlsx')->saveMode(overwrite()))
->run();

data_frame()
->read(from_excel(__DIR__ . '/orders.xlsx'))
->select('id', 'email', 'amount')
->limit(3)
->write(to_output(truncate: false))
->run();
```

```text
+----+-----------------------+--------+
| id | email | amount |
+----+-----------------------+--------+
| 1 | customer1@example.com | 0.1 |
| 2 | customer2@example.com | 0.2 |
| 3 | customer3@example.com | 0.3 |
+----+-----------------------+--------+
3 rows
```

[`from_dbal_key_set_qb`](/documentation/dsl/doctrine/from-dbal-key-set-qb) reads the table page by page, and every page starts where the previous one ended.
[`to_excel`](/documentation/dsl/excel/to-excel) writes every order to the file right away, so nothing piles up in memory.
The second pipeline is there only to show us the first three rows of the file we just created.

`$database` is a Doctrine DBAL connection, so the same script exports a table from MySQL or PostgreSQL. Only the connection parameters change.

## How much memory does an Excel export take in PHP

PHP 8.3, `memory_limit=128M`, orders with five columns:

| Orders | Code | Peak memory | Time |
|-----------|----------------|---------------------------|------|
| 100,000 | PhpSpreadsheet | 367Mb, without the limit | 8.7s |
| 100,000 | Flow | 28Mb | 3.8s |
| 1,000,000 | PhpSpreadsheet | fatal error, needs 3663Mb | 98s |
| 1,000,000 | Flow | 28Mb | 29s |

Ten times more orders cost Flow nothing. They cost PhpSpreadsheet 3296Mb.

To check it on your machine, add this line at the end of any of the scripts above:

```php ignore
printf("peak memory: %.1f MB\n", memory_get_peak_usage(true) / 1024 / 1024);
```
Loading