diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index a9b524a855..c113175cff 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -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 ." diff --git a/web/landing/.gitignore b/web/landing/.gitignore index c673265b51..bcb9e5bdec 100644 --- a/web/landing/.gitignore +++ b/web/landing/.gitignore @@ -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 diff --git a/web/landing/assets/controllers/code_tabs_controller.js b/web/landing/assets/controllers/code_tabs_controller.js new file mode 100644 index 0000000000..104f689db9 --- /dev/null +++ b/web/landing/assets/controllers/code_tabs_controller.js @@ -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; + } + } +} diff --git a/web/landing/assets/styles/app.css b/web/landing/assets/styles/app.css index ef84d53b01..82d3389c9b 100644 --- a/web/landing/assets/styles/app.css +++ b/web/landing/assets/styles/app.css @@ -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; diff --git a/web/landing/config/services.yaml b/web/landing/config/services.yaml index 413f899b61..11e387e3a8 100644 --- a/web/landing/config/services.yaml +++ b/web/landing/config/services.yaml @@ -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'] @@ -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] diff --git a/web/landing/content/guides/export-database-to-excel-in-php.md b/web/landing/content/guides/export-database-to-excel-in-php.md new file mode 100644 index 0000000000..4cc689f3be --- /dev/null +++ b/web/landing/content/guides/export-database-to-excel-in-php.md @@ -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 +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 +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 + '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); +``` diff --git a/web/landing/content/guides/import-csv-file-into-mysql-or-postgresql-in-php.md b/web/landing/content/guides/import-csv-file-into-mysql-or-postgresql-in-php.md new file mode 100644 index 0000000000..d715d9223c --- /dev/null +++ b/web/landing/content/guides/import-csv-file-into-mysql-or-postgresql-in-php.md @@ -0,0 +1,285 @@ +--- +seo_title: 'Import a CSV file into MySQL or PostgreSQL in PHP, with upsert' +seo_description: 'Import a CSV file into a MySQL or PostgreSQL table in PHP, a hundred thousand rows in under three seconds, and update the rows that are already there with an upsert.' +group: Importing data +problem: 'One INSERT per row takes minutes' +proof_label: '100,000 rows into MySQL' +proof_before: '264s' +proof_after: '2.3s' +featured: true +published: '2026-11-18' +updated: '2026-11-18' +--- + +# Import a CSV file into MySQL or PostgreSQL in PHP + +Let's say a CSV file with orders lands on our server every night, and we need to put it into the `orders` table. +Some of the orders are new, and some of them changed since yesterday. + +> The scripts that talk to a database don't run in the playground. Run them on your machine. + +## The file + +First we need a file to import, so let's generate one. +Set `$rows` to `100_000` to get the version we measure below. + +```php +execute( + create()->table('orders') + ->ifNotExists() + ->column(column('id', column_type_bigint())->primaryKey()) + ->column(column('email', column_type_text())->notNull()) + ->column(column('country', column_type_text())->notNull()) + ->column(column('amount', column_type_numeric(10, 2))->notNull()) + ->column(column('created_at', column_type_timestamp())->notNull()) +); +``` + +The third tab creates the same PostgreSQL table with [flow-php/postgresql](/documentation/components/libs/postgresql), Flow's own PostgreSQL library. It has a query builder, so there is no SQL string in the script. + +## Import a CSV file with one INSERT per row + +The import everybody writes first: read a row, insert a row. + +```php ignore tab="MySQL" + PDO::ERRMODE_EXCEPTION]); +$insert = $database->prepare('INSERT INTO orders (id, email, country, amount, created_at) VALUES (?, ?, ?, ?, ?)'); + +$file = fopen(__DIR__ . '/orders.csv', 'r'); +fgetcsv($file, escape: ''); + +while (($row = fgetcsv($file, escape: '')) !== false) { + $insert->execute($row); +} + +fclose($file); +``` + +```php ignore tab="PostgreSQL" + PDO::ERRMODE_EXCEPTION]); +$insert = $database->prepare('INSERT INTO orders (id, email, country, amount, created_at) VALUES (?, ?, ?, ?, ?)'); + +$file = fopen(__DIR__ . '/orders.csv', 'r'); +fgetcsv($file, escape: ''); + +while (($row = fgetcsv($file, escape: '')) !== false) { + $insert->execute($row); +} + +fclose($file); +``` + +It works. For a hundred thousand orders it takes two minutes in PostgreSQL and more than four minutes in MySQL, because every order is a separate trip to the database. + +## The second night it ends with a duplicate key error + +The next night the file comes again, with the same orders and a few new ones: + +```text tab="MySQL" +Fatal error: Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1' for key 'orders.PRIMARY' +``` + +```text tab="PostgreSQL" +Fatal error: Uncaught PDOException: SQLSTATE[23505]: Unique violation: 7 ERROR: duplicate key value violates unique constraint "orders_pkey" +DETAIL: Key (id)=(1) already exists. +``` + +The first order is already in the table, so the import stops at the first row. +What we need is an upsert: insert the order when it's new, update it when it's already there. +The SQL for that is different in every database. It's `ON DUPLICATE KEY UPDATE` in MySQL and `ON CONFLICT ... DO UPDATE` in PostgreSQL. + +## Import and upsert a CSV file with Flow + +Flow needs PHP 8.3 or newer. + +```bash tab="Doctrine MySQL" +composer require flow-php/etl flow-php/etl-adapter-csv flow-php/etl-adapter-doctrine +``` + +```bash tab="Doctrine PostgreSQL" +composer require flow-php/etl flow-php/etl-adapter-csv flow-php/etl-adapter-doctrine +``` + +```bash tab="Flow PostgreSQL" +composer require flow-php/etl flow-php/etl-adapter-csv flow-php/etl-adapter-postgresql +``` + +And this is the whole import: + +```php ignore tab="Doctrine MySQL" + 'pdo_mysql', + 'host' => '127.0.0.1', + 'dbname' => 'shop', + 'user' => 'shop', + 'password' => 'secret', +]); + +data_frame() + ->read(from_csv(__DIR__ . '/orders.csv')) + ->write(to_dbal_table_insert($database, 'orders', mysql_insert_options( + upsert: true, + update_columns: ['email', 'country', 'amount', 'created_at'], + ))) + ->run(); +``` + +```php ignore tab="Doctrine PostgreSQL" + 'pdo_pgsql', + 'host' => '127.0.0.1', + 'dbname' => 'shop', + 'user' => 'shop', + 'password' => 'secret', +]); + +data_frame() + ->read(from_csv(__DIR__ . '/orders.csv')) + ->write(to_dbal_table_insert($database, 'orders', postgresql_insert_options( + conflict_columns: ['id'], + update_columns: ['email', 'country', 'amount', 'created_at'], + ))) + ->run(); +``` + +```php ignore tab="Flow PostgreSQL" +read(from_csv(__DIR__ . '/orders.csv')) + ->write(to_pgsql_table($client, 'orders')->withInsertOptions(pgsql_insert_options( + conflictColumns: ['id'], + updateColumns: ['email', 'country', 'amount', 'created_at'], + ))) + ->run(); +``` + +Flow doesn't send the orders one by one. It sends them in batches, many orders in one trip to the database. + +The upsert is one option. We say which column tells us that the order is already there, and which columns to update, and Flow writes the right SQL for the database we use. +We can run the same script every night: new orders are inserted, and the ones that changed are updated. + +The third tab doesn't use Doctrine. It writes through flow-php/postgresql, the same library that created the table above. + +## How long does a CSV import take in PHP + +PHP 8.3, a hundred thousand orders with five columns, the databases in Docker: + +| Code | MySQL | PostgreSQL | +|--------------------------------------|-------|------------| +| One `INSERT` per row | 264s | 120s | +| Flow with Doctrine | 2.3s | 2.5s | +| Flow with Doctrine, the second night | 1.9s | 2.7s | +| Flow PostgreSQL | - | 2.3s | +| Flow PostgreSQL, the second night | - | 2.5s | diff --git a/web/landing/content/guides/import-data-from-rest-api-in-php.md b/web/landing/content/guides/import-data-from-rest-api-in-php.md new file mode 100644 index 0000000000..f65a9bf00b --- /dev/null +++ b/web/landing/content/guides/import-data-from-rest-api-in-php.md @@ -0,0 +1,261 @@ +--- +seo_title: 'Consume a paginated REST API in PHP and keep the raw responses' +seo_description: 'Import data from a paginated REST API into a database in PHP without a pagination loop, and store every raw response, so we always know what the API sent.' +group: Importing data +problem: 'Nobody knows what the API sent' +published: '2026-11-18' +updated: '2026-11-18' +--- + +# Import data from a REST API in PHP and keep the raw responses + +Let's say our orders live in somebody else's system, and every night we pull them from its REST API into the `orders` table. +The API gives a hundred orders per page, and it wants a token. + +> These scripts need an API and a database, so they run only on your machine, not in the playground. + +## The API + +First we need an API to call, so let's create one. It's a single file for the web server that comes with PHP. + +```php ignore + 'invalid token']); + + return; +} + +$total = 250; +$page = max(1, (int) ($_GET['page'] ?? 1)); +$orders = []; + +for ($id = ($page - 1) * 100 + 1; $id <= min($total, $page * 100); $id++) { + $orders[] = [ + 'id' => $id, + 'email' => "customer{$id}@example.com", + 'country' => ['PL', 'US', 'DE', 'FR', 'GB'][$id % 5], + 'amount' => ($id % 1000) / 10, + 'created_at' => gmdate('Y-m-d H:i:s', 1_700_000_000 + $id * 60), + ]; +} + +echo json_encode(['data' => $orders, 'meta' => ['page' => $page, 'total' => $total]]); +``` + +```bash +php -S 127.0.0.1:8080 api.php +``` + +The `orders` table is the same as in [Import a CSV file into MySQL or PostgreSQL](/guides/import-csv-file-into-mysql-or-postgresql-in-php#the-table). + +## Call a REST API in PHP with Guzzle + +The first thing that comes to mind is a loop: ask for a page, decode it, insert the orders, ask for the next one. + +```bash +composer require guzzlehttp/guzzle +``` + +```php ignore + 'http://127.0.0.1:8080', + 'headers' => ['Authorization' => 'Bearer secret-token'], +]); + +$database = new PDO('mysql:host=127.0.0.1;dbname=shop', 'shop', 'secret'); +$insert = $database->prepare( + 'INSERT INTO orders (id, email, country, amount, created_at) VALUES (?, ?, ?, ?, ?) + ON DUPLICATE KEY UPDATE email = VALUES(email), country = VALUES(country), amount = VALUES(amount), created_at = VALUES(created_at)' +); + +$page = 1; + +do { + $response = $api->get('/orders', ['query' => ['page' => $page]]); + $orders = json_decode((string) $response->getBody(), true)['data']; + + foreach ($orders as $order) { + $insert->execute([$order['id'], $order['email'], $order['country'], $order['amount'], $order['created_at']]); + } + + $page++; +} while ($orders !== []); +``` + +It works, all 250 orders are in the table. + +## Three weeks later an amount is wrong + +Somebody from finance asks why order 187 has a different amount in our table than in the invoice. +Was it the API, or our code? + +We can't tell. The response went through `json_decode` and five array keys into an `INSERT`, and after that it was gone. +The API shows today's version of the order, not the one it sent us three weeks ago. + +With an SDK in place of Guzzle it's the same, only with objects between the response and the table. + +So the import needs to keep what the API said. That means more code in the loop: a file to write to, the status code, the failed requests. +And the loop itself has to change for every API, because every API paginates in its own way. + +## Consume the API with Flow + +Flow needs PHP 8.3 or newer. + +```bash +composer require flow-php/etl flow-php/etl-adapter-http flow-php/etl-adapter-json flow-php/etl-adapter-doctrine symfony/http-client nyholm/psr7 +``` + +```php ignore + 'pdo_mysql', + 'host' => '127.0.0.1', + 'dbname' => 'shop', + 'user' => 'shop', + 'password' => 'secret', +]); + +$order = type_structure([ + 'id' => type_integer(), + 'email' => type_string(), + 'country' => type_string(), + 'amount' => type_float(), + 'created_at' => type_string(), +]); + +data_frame() + ->read(from_http_paginated( + new Psr18Client(), + (new Psr17Factory()) + ->createRequest('GET', 'http://127.0.0.1:8080/orders') + ->withHeader('Authorization', 'Bearer secret-token'), + http_pagination_page_number(http_request_option_query('page'), records_path: 'data'), + )) + ->write(to_transformation( + select('request_uri', 'response_status_code', 'response_body'), + to_json_lines(__DIR__ . '/responses-' . date('Y-m-d') . '.jsonl')->saveMode(overwrite()), + )) + ->write(to_branch( + ref('response_status_code')->greaterThanEqual(lit(400)), + to_transformation( + select('request_uri', 'response_status_code', 'response_body'), + to_json_lines(__DIR__ . '/failed-' . date('Y-m-d') . '.jsonl')->saveMode(overwrite()), + ), + )) + ->filter(ref('response_status_code')->lessThan(lit(400))) + ->withColumn('body', ref('response_body')->jsonDecode()->unpack(schema(list_schema('data', type_list($order))))) + ->withColumn('order', ref('body.data')->expand()) + ->withColumn('order', ref('order')->unpack(schema( + int_schema('id'), + str_schema('email'), + str_schema('country'), + float_schema('amount'), + datetime_schema('created_at'), + ))) + ->select( + ref('order.id')->as('id'), + ref('order.email')->as('email'), + ref('order.country')->as('country'), + ref('order.amount')->as('amount'), + ref('order.created_at')->as('created_at'), + ) + ->write(to_dbal_table_insert($database, 'orders', mysql_insert_options( + upsert: true, + update_columns: ['email', 'country', 'amount', 'created_at'], + ))) + ->run(); +``` + +There is no loop. [`from_http_paginated`](/documentation/components/adapters/http) asks for `?page=1`, `?page=2` and so on, until the `data` of a response is empty. +Every response is one row, with the body exactly as the API sent it, the status code, the headers and the request that asked for it. + +## Keep every raw response + +The first `write` is the archive. It takes three columns of every response and puts them in a file with today's date, one response per line: + +```text +{"request_uri":"http:\/\/127.0.0.1:8080\/orders?page=1","response_status_code":200,"response_body":"{\"data\":[{\"id\":1,\"email\":\"customer1@example.com\", ... +{"request_uri":"http:\/\/127.0.0.1:8080\/orders?page=2","response_status_code":200,"response_body":"{\"data\":[{\"id\":101,\"email\":\"customer101@example.com\", ... +{"request_uri":"http:\/\/127.0.0.1:8080\/orders?page=3","response_status_code":200,"response_body":"{\"data\":[{\"id\":201,\"email\":\"customer201@example.com\", ... +{"request_uri":"http:\/\/127.0.0.1:8080\/orders?page=4","response_status_code":200,"response_body":"{\"data\":[],\"meta\":{\"page\":4,\"total\":250}}"} +``` + +When finance asks about order 187, the answer is in the file from that night. + +A `write` in the middle doesn't end anything. The same rows go on to the next step, so the archive and the import are one run and one pass over the API. + +## Put the failed requests aside + +The second `write` is a branch. [`to_branch`](/documentation/dsl/core/to-branch) takes a condition, and only the responses that match it go to its file. + +With a wrong token the API answers 401. Guzzle throws an exception. Flow stops asking, and the response is in `failed-2026-11-18.jsonl`: + +```text +{"request_uri":"http:\/\/127.0.0.1:8080\/orders?page=1","response_status_code":401,"response_body":"{\"error\":\"invalid token\"}"} +``` + +Nothing goes into the table, because the `filter` right after it lets only the good responses through. + +## From responses to orders in the table + +The rest turns pages into orders: + +- `jsonDecode()->unpack(...)` decodes the body and says what is in it, a list of orders under `data` +- `expand()` makes one row per order out of one row per page +- the second `unpack` gives every order its columns and types, so `created_at` is a date and not a string +- `to_dbal_table_insert` with `upsert: true` inserts the new orders and updates the ones that changed, the same as in the [CSV import](/guides/import-csv-file-into-mysql-or-postgresql-in-php) + +## A different API, a different pagination + +Not every API counts pages. With the loop written by hand that means writing the loop again. +Here it's one argument: + +```php ignore tab="Page number" +http_pagination_page_number(http_request_option_query('page'), records_path: 'data') +``` + +```php ignore tab="Offset" +http_pagination_offset( + http_request_option_query('offset'), + http_request_option_query('limit'), + limit: 100, + total_path: 'meta.total', +) +``` + +```php ignore tab="Cursor" +http_pagination_cursor('meta.next_cursor', http_request_option_query('cursor')) +``` + +```php ignore tab="Link header" +http_pagination_link_header('next') +``` diff --git a/web/landing/content/guides/import-large-excel-file-in-php.md b/web/landing/content/guides/import-large-excel-file-in-php.md new file mode 100644 index 0000000000..a3935412f4 --- /dev/null +++ b/web/landing/content/guides/import-large-excel-file-in-php.md @@ -0,0 +1,171 @@ +--- +seo_title: 'PhpSpreadsheet out of memory: import a large Excel file in PHP' +seo_description: 'PhpSpreadsheet builds an object for every cell, so a 3Mb Excel file runs out of memory. Why it happens, and how to read a million rows from XLSX in PHP with 26Mb.' +group: Importing data +problem: 'A 3Mb Excel file does not fit in 128Mb' +proof_label: 'Reading a 2.6Mb Excel file' +proof_before: '430Mb' +proof_after: '26Mb' +published: '2026-11-18' +updated: '2026-11-18' +--- + +# Import a large Excel file in PHP without running out of memory + +Let's say a customer uploads their orders as an Excel file, and we need the revenue per country before we import them. +The file has a hundred thousand rows and it's small, 2.6Mb. Our PHP process runs with the default `memory_limit` of 128Mb. + +## The file + +First we need a file to read, so let's create one. +Set `$rows` to `100_000` to get the 2.6Mb version. + +```php + $id, + 'email' => "customer{$id}@example.com", + 'country' => ['PL', 'US', 'DE', 'FR', 'GB'][$id % 5], + 'amount' => ($id % 1000) / 10, + 'created_at' => gmdate('Y-m-d H:i:s', 1_700_000_000 + $id * 60), + ]; +} + +data_frame() + ->read(from_array($orders)) + ->write(to_excel(__DIR__ . '/orders.xlsx')->saveMode(overwrite())) + ->run(); + +echo "orders.xlsx: {$rows} rows\n"; +``` + +```text output +orders.xlsx: 1000 rows +``` + +## Read an Excel file with PhpSpreadsheet + +The first thing that comes to mind is PhpSpreadsheet: load the file and take the rows as an array. + +> PhpSpreadsheet is not available in the playground, so this script runs only on your machine. + +```bash +composer require phpoffice/phpspreadsheet +``` + +```php ignore +getActiveSheet(); +$revenue = []; + +foreach ($sheet->toArray() as $number => $row) { + if ($number === 0) { + continue; + } + + $revenue[$row[2]] = ($revenue[$row[2]] ?? 0.0) + (float) $row[3]; +} + +arsort($revenue); + +foreach ($revenue as $country => $total) { + printf("%s %.2f\n", $country, $total); +} +``` + +With a thousand rows it works. With a hundred thousand rows it ends like this: + +```text +Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 4096 bytes) +``` + +## Why a 3Mb Excel file ends with "Allowed memory size exhausted" + +How can a file of 2.6Mb not fit in 128Mb? + +An Excel file is a zip archive with XML inside, so it's much bigger than it looks. +And PhpSpreadsheet builds an object for every cell of the whole workbook before we get the first row. For our file that is 430Mb, more than 150 times the size of the file. + +Laravel Excel (`maatwebsite/excel`) is built on PhpSpreadsheet, so the same reader is underneath. + +## Read a large Excel file with Flow + +Flow needs PHP 8.3 or newer. + +```bash +composer require flow-php/etl flow-php/etl-adapter-excel +``` + +```php +read(from_excel(__DIR__ . '/orders.xlsx')) + ->groupBy([ref('country')]) + ->aggregate(sum(ref('amount'))) + ->sortBy(ref('amount_sum')->desc()) + ->write(to_output(truncate: false)) + ->run(); +``` + +```text output ++---------+--------------+ +| country | amount_sum | ++---------+--------------+ +| GB | 10030.000000 | +| FR | 10010.000000 | +| DE | 9990.000000 | +| US | 9970.000000 | +| PL | 9950.000000 | ++---------+--------------+ +5 rows +``` + +[`from_excel`](/documentation/dsl/excel/from-excel) reads the sheet row by row, so the workbook is never in memory as a whole. +`groupBy` with [`sum`](/documentation/dsl/core/sum) adds up the amounts per country, and `sortBy` puts the biggest one first. + +From here, putting the orders into a database is the same as in [Import a CSV file into MySQL or PostgreSQL](/guides/import-csv-file-into-mysql-or-postgresql-in-php). Only the reader changes, `from_excel` in place of `from_csv`. + +## How much memory does reading an Excel file take in PHP + +PHP 8.3, `memory_limit=128M`, orders with five columns: + +| Rows | File size | Code | Peak memory | Time | +|-----------|-----------|----------------|--------------------------|------| +| 100,000 | 2.6Mb | PhpSpreadsheet | fatal error, needs 430Mb | 8.0s | +| 100,000 | 2.6Mb | Flow | 26Mb | 3.7s | +| 1,000,000 | 26Mb | Flow | 26Mb | 30s | + +Ten times more rows cost Flow nothing. + +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); +``` diff --git a/web/landing/content/guides/index-database-table-in-elasticsearch-with-php.md b/web/landing/content/guides/index-database-table-in-elasticsearch-with-php.md new file mode 100644 index 0000000000..27fbd80cce --- /dev/null +++ b/web/landing/content/guides/index-database-table-in-elasticsearch-with-php.md @@ -0,0 +1,477 @@ +--- +seo_title: 'Elasticsearch in PHP: index a MySQL or PostgreSQL table and search it' +seo_description: 'LIKE finds nothing when the words change order. How to index a MySQL or PostgreSQL table in Elasticsearch or Meilisearch with PHP, and search it.' +group: Search +problem: 'LIKE finds nothing when the words change order' +proof_label: '100,000 products indexed' +proof_after: '4s' +published: '2026-11-18' +updated: '2026-11-18' +--- + +# Build a search in PHP: index a database table in Elasticsearch + +Let's say we have a shop with a hundred thousand products in MySQL or PostgreSQL, and the search box on the page runs a `LIKE` query. +It worked fine for the first hundred products. + +> These scripts need a database and Elasticsearch, so they run only on your machine, not in the playground. + +## The table + +First we need products to search, so let's create them. + +```php ignore tab="MySQL" +exec('DROP TABLE IF EXISTS products'); +$database->exec( + 'CREATE TABLE products ( + id BIGINT PRIMARY KEY, + name VARCHAR(255) NOT NULL, + description TEXT NOT NULL, + category VARCHAR(64) NOT NULL, + price DECIMAL(10, 2) NOT NULL + )' +); + +$rows = 100_000; +$features = ['Wireless', 'Mechanical', 'Compact', 'Ergonomic', 'Gaming', 'Silent', 'Portable', 'Backlit']; +$colors = ['Black', 'White', 'Silver', 'Red', 'Blue']; +$products = ['Keyboard' => 'peripherals', 'Mouse' => 'peripherals', 'Monitor' => 'displays', 'Webcam' => 'video', 'Headset' => 'audio']; +$names = array_keys($products); + +$insert = $database->prepare('INSERT INTO products (id, name, description, category, price) VALUES (?, ?, ?, ?, ?)'); +$database->beginTransaction(); + +for ($id = 1; $id <= $rows; $id++) { + $product = $names[$id % 5]; + $first = $features[$id % 8]; + $second = $features[intdiv($id, 8) % 8]; + $color = $colors[intdiv($id, 5) % 5]; + + $insert->execute([ + $id, + "{$first} {$color} {$product} {$id}", + "A {$second} {$product} for the office and for home, with two years of warranty.", + $products[$product], + ($id % 500) + 9.99, + ]); +} + +$database->commit(); + +echo "products: {$rows} rows\n"; +``` + +```php ignore tab="PostgreSQL" +exec('DROP TABLE IF EXISTS products'); +$database->exec( + 'CREATE TABLE products ( + id BIGINT PRIMARY KEY, + name VARCHAR(255) NOT NULL, + description TEXT NOT NULL, + category VARCHAR(64) NOT NULL, + price DECIMAL(10, 2) NOT NULL + )' +); + +$rows = 100_000; +$features = ['Wireless', 'Mechanical', 'Compact', 'Ergonomic', 'Gaming', 'Silent', 'Portable', 'Backlit']; +$colors = ['Black', 'White', 'Silver', 'Red', 'Blue']; +$products = ['Keyboard' => 'peripherals', 'Mouse' => 'peripherals', 'Monitor' => 'displays', 'Webcam' => 'video', 'Headset' => 'audio']; +$names = array_keys($products); + +$insert = $database->prepare('INSERT INTO products (id, name, description, category, price) VALUES (?, ?, ?, ?, ?)'); +$database->beginTransaction(); + +for ($id = 1; $id <= $rows; $id++) { + $product = $names[$id % 5]; + $first = $features[$id % 8]; + $second = $features[intdiv($id, 8) % 8]; + $color = $colors[intdiv($id, 5) % 5]; + + $insert->execute([ + $id, + "{$first} {$color} {$product} {$id}", + "A {$second} {$product} for the office and for home, with two years of warranty.", + $products[$product], + ($id % 500) + 9.99, + ]); +} + +$database->commit(); + +echo "products: {$rows} rows\n"; +``` + +```text +products: 100000 rows +``` + +## Search a database table in PHP with LIKE + +The first thing that comes to mind is `LIKE` with a percent sign on both sides. In PostgreSQL it's `ILIKE`, because `LIKE` there cares about upper and lower case. + +```php ignore tab="MySQL" +prepare('SELECT id, name, price FROM products WHERE name LIKE ? OR description LIKE ? LIMIT 5'); + +foreach (['wireless black keyboard', 'black wireless keyboard'] as $query) { + $search->execute(["%{$query}%", "%{$query}%"]); + echo $query, ":\n"; + + foreach ($search->fetchAll(PDO::FETCH_ASSOC) as $product) { + printf(" %d %s %.2f\n", $product['id'], $product['name'], $product['price']); + } +} +``` + +```php ignore tab="PostgreSQL" +prepare('SELECT id, name, price FROM products WHERE name ILIKE ? OR description ILIKE ? LIMIT 5'); + +foreach (['wireless black keyboard', 'black wireless keyboard'] as $query) { + $search->execute(["%{$query}%", "%{$query}%"]); + echo $query, ":\n"; + + foreach ($search->fetchAll(PDO::FETCH_ASSOC) as $product) { + printf(" %d %s %.2f\n", $product['id'], $product['name'], $product['price']); + } +} +``` + +```text +wireless black keyboard: + 200 Wireless Black Keyboard 200 209.99 + 400 Wireless Black Keyboard 400 409.99 + 600 Wireless Black Keyboard 600 109.99 + 800 Wireless Black Keyboard 800 309.99 + 1000 Wireless Black Keyboard 1000 9.99 +black wireless keyboard: +``` + +## Why LIKE is not a search + +The same three words in a different order, and the shop has no keyboards. + +`LIKE` doesn't know about words. It looks for one exact piece of text, so the customer has to type the name the way we wrote it. +It also can't tell which product fits better. One has the word in its name, the other only mentions it in the description. + +That's what a search engine is for. But a search engine has its own copy of the data, so now there is something to build: read the products from the database, send them to Elasticsearch in bulks, and do it again whenever they change. + +## Index a database table in Elasticsearch with Flow + +Flow needs PHP 8.3 or newer. It talks to search engines through [SEAL](https://php-cmsig.github.io/search/), a library with one API for Elasticsearch, OpenSearch, Meilisearch, Algolia, Solr, Typesense and a few more. + +It reads the table through Doctrine DBAL, or for PostgreSQL through [flow-php/postgresql](/documentation/components/libs/postgresql), Flow's own client with a query builder. + +```bash tab="Doctrine MySQL" +composer require flow-php/etl flow-php/etl-adapter-doctrine flow-php/etl-adapter-seal cmsig/seal-elasticsearch-adapter +``` + +```bash tab="Doctrine PostgreSQL" +composer require flow-php/etl flow-php/etl-adapter-doctrine flow-php/etl-adapter-seal cmsig/seal-elasticsearch-adapter +``` + +```bash tab="Flow PostgreSQL" +composer require flow-php/etl flow-php/etl-adapter-postgresql flow-php/etl-adapter-seal cmsig/seal-elasticsearch-adapter +``` + +And this is the whole indexer: + +```php ignore tab="Doctrine MySQL" + 'pdo_mysql', + 'host' => '127.0.0.1', + 'dbname' => 'shop', + 'user' => 'shop', + 'password' => 'secret', +]); + +$products = schema( + str_schema('id'), + str_schema('name'), + str_schema('description'), + str_schema('category', metadata: SealMetadata::filterable()), + float_schema('price'), +); + +$engine = new Engine( + new ElasticsearchAdapter(ClientBuilder::create()->setHosts(['http://127.0.0.1:9200'])->build()), + to_seal_schema($products, index_name: 'products', identifier: 'id'), +); + +if (!$engine->existIndex('products')) { + $engine->createIndex('products'); +} + +data_frame() + ->read( + from_dbal_key_set_qb( + $database, + $database->createQueryBuilder() + ->select('id', 'name', 'description', 'category', 'price') + ->from('products'), + pagination_key_set(pagination_key_asc('id')), + )->withSchema($products) + ) + ->write(to_seal_upsert($engine, 'products')->withBulkSize(1000)) + ->run(); +``` + +```php ignore tab="Doctrine PostgreSQL" + 'pdo_pgsql', + 'host' => '127.0.0.1', + 'dbname' => 'shop', + 'user' => 'shop', + 'password' => 'secret', +]); + +$products = schema( + str_schema('id'), + str_schema('name'), + str_schema('description'), + str_schema('category', metadata: SealMetadata::filterable()), + float_schema('price'), +); + +$engine = new Engine( + new ElasticsearchAdapter(ClientBuilder::create()->setHosts(['http://127.0.0.1:9200'])->build()), + to_seal_schema($products, index_name: 'products', identifier: 'id'), +); + +if (!$engine->existIndex('products')) { + $engine->createIndex('products'); +} + +data_frame() + ->read( + from_dbal_key_set_qb( + $database, + $database->createQueryBuilder() + ->select('id', 'name', 'description', 'category', 'price') + ->from('products'), + pagination_key_set(pagination_key_asc('id')), + )->withSchema($products) + ) + ->write(to_seal_upsert($engine, 'products')->withBulkSize(1000)) + ->run(); +``` + +```php ignore tab="Flow PostgreSQL" +setHosts(['http://127.0.0.1:9200'])->build()), + to_seal_schema($products, index_name: 'products', identifier: 'id'), +); + +if (!$engine->existIndex('products')) { + $engine->createIndex('products'); +} + +data_frame() + ->read( + from_pgsql_key_set( + $client, + select(col('id'), col('name'), col('description'), col('category'), col('price'))->from(table('products')), + pgsql_pagination_key_set(pgsql_pagination_key_asc('id')), + )->withSchema($products) + ) + ->write(to_seal_upsert($engine, 'products')->withBulkSize(1000)) + ->run(); +``` + +A hundred thousand products are in the index after three to four seconds, from either database. + +The schema is written once and used twice. [`to_seal_schema`](/documentation/components/adapters/seal) makes the index out of it: text columns can be searched, `price` can be sorted and filtered, and `category` can be filtered because we said so. +The reader uses the same schema to give the columns their types. + +The keyset reader takes the table page by page, so the products are never in memory all at once. +[`to_seal_upsert`](/documentation/components/adapters/seal) sends them in bulks of a thousand. + +## Search the index + +Now the search box asks Elasticsearch, with a filter on the category. This script is the same for every database: + +```php ignore +setHosts(['http://127.0.0.1:9200'])->build()), + to_seal_schema( + schema( + str_schema('id'), + str_schema('name'), + str_schema('description'), + str_schema('category', metadata: SealMetadata::filterable()), + float_schema('price'), + ), + index_name: 'products', + identifier: 'id', + ), +); + +foreach (['wireless black keyboard', 'black wireless keyboard'] as $query) { + $result = $engine->createSearchBuilder('products') + ->addFilter(new SearchCondition($query)) + ->addFilter(new EqualCondition('category', 'peripherals')) + ->limit(5) + ->getResult(); + + echo $query, ":\n"; + + foreach ($result as $product) { + printf(" %s %s %.2f\n", $product['id'], $product['name'], $product['price']); + } +} +``` + +```text +wireless black keyboard: + 200 Wireless Black Keyboard 200 209.99 + 400 Wireless Black Keyboard 400 409.99 + 600 Wireless Black Keyboard 600 109.99 + 800 Wireless Black Keyboard 800 309.99 + 1000 Wireless Black Keyboard 1000 9.99 +black wireless keyboard: + 200 Wireless Black Keyboard 200 209.99 + 400 Wireless Black Keyboard 400 409.99 + 600 Wireless Black Keyboard 600 109.99 + 800 Wireless Black Keyboard 800 309.99 + 1000 Wireless Black Keyboard 1000 9.99 +``` + +Both orders of the words find the keyboards. + +## Change the search engine + +Elasticsearch is not the only choice, and with SEAL it's not a decision for life. +To move the same search to Meilisearch, install its adapter: + +```bash tab="Elasticsearch" +composer require cmsig/seal-elasticsearch-adapter +``` + +```bash tab="Meilisearch" +composer require cmsig/seal-meilisearch-adapter +``` + +And change how the engine gets its adapter, in both scripts: + +```php ignore tab="Elasticsearch" +use CmsIg\Seal\Adapter\Elasticsearch\ElasticsearchAdapter; +use Elastic\Elasticsearch\ClientBuilder; + +new ElasticsearchAdapter(ClientBuilder::create()->setHosts(['http://127.0.0.1:9200'])->build()) +``` + +```php ignore tab="Meilisearch" +use CmsIg\Seal\Adapter\Meilisearch\MeilisearchAdapter; +use Meilisearch\Client; + +new MeilisearchAdapter(new Client('http://127.0.0.1:7700', 'masterKey')) +``` + +The schema, the reader, `to_seal_upsert` and the search stay as they are. + +## Keep the index up to date + +Products change, so the index has to follow. + +The script above is already an upsert. A product that is in the index gets replaced, and a new one gets added, so we can run it every night as it is. +To send only what changed, add a `where` to the query, for example on an `updated_at` column. + +Products that are gone from the table need one more step. [`to_seal_delete`](/documentation/components/adapters/seal) takes their ids and removes them from the index: + +```php ignore +use function Flow\ETL\Adapter\Seal\to_seal_delete; +use function Flow\ETL\DSL\{data_frame, from_array}; + +data_frame() + ->read(from_array([['id' => '200'], ['id' => '400']])) + ->write(to_seal_delete($engine, 'products')) + ->run(); +``` diff --git a/web/landing/content/guides/read-large-csv-file-in-php.md b/web/landing/content/guides/read-large-csv-file-in-php.md new file mode 100644 index 0000000000..454b1e7bea --- /dev/null +++ b/web/landing/content/guides/read-large-csv-file-in-php.md @@ -0,0 +1,289 @@ +--- +seo_title: Read a large CSV file in PHP without running out of memory +seo_description: 'A CSV file bigger than the memory limit ends with "Allowed memory size exhausted". Why file() fails, how fgetcsv fixes it and what Flow adds, with code that runs.' +group: Reading files +problem: 'file() and usort() run out of memory' +proof_label: 'Sorting a million rows' +proof_before: '624Mb' +proof_after: '98Mb' +published: '2026-11-18' +updated: '2026-11-18' +--- + +# Read a large CSV file in PHP without running out of memory + +Let's say we got an export of orders: one CSV file, a million rows, 62Mb. +We need the revenue per country, and our PHP process runs with the default `memory_limit` of 128Mb. + +Doesn't look like a complicated task, right? + +## The file + +First we need a file to work with, so let's generate one. +Set `$rows` to `1_000_000` to get the 62Mb version. + +```php + $line) { + if ($number === 0) { + continue; + } + + $row = str_getcsv($line, escape: ''); + $revenue[$row[2]] = ($revenue[$row[2]] ?? 0.0) + (float) $row[3]; +} + +arsort($revenue); + +foreach ($revenue as $country => $total) { + printf("%s %.2f\n", $country, $total); +} +``` + +```text output +GB 10030.00 +FR 10010.00 +DE 9990.00 +US 9970.00 +PL 9950.00 +``` + +With a thousand rows it works. With a million rows it ends like this: + +```text +Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 16777224 bytes) +``` + +`file()` keeps every line in memory at the same time. For our file that is 172Mb, and we have 128Mb. +We could raise `memory_limit`, but that only moves the problem to the next, bigger file. + +## Read the CSV file line by line with fgetcsv + +`fgetcsv` reads one row at a time, so it doesn't matter how big the file is. + +```php + $total) { + printf("%s %.2f\n", $country, $total); +} +``` + +```text output +GB 10030.00 +FR 10010.00 +DE 9990.00 +US 9970.00 +PL 9950.00 +``` + +That's 2Mb of memory for a million rows. Reading a big file was never the hard part. + +## Now sort it + +OK, but the next request comes the same day: the same file, sorted by amount, the biggest orders first. + +We can't sort a file one row at a time. To sort the rows we need all of them, so we are back to keeping the whole file in memory. + +```php + (float) $right['amount'] <=> (float) $left['amount']); + +$sorted = fopen(__DIR__ . '/orders-sorted.csv', 'w'); +fputcsv($sorted, $header, escape: ''); + +foreach ($orders as $order) { + fputcsv($sorted, $order, escape: ''); +} + +fclose($sorted); + +foreach (array_slice($orders, 0, 3) as $order) { + printf("%s %s %s\n", $order['id'], $order['email'], $order['amount']); +} +``` + +```text output +999 customer999@example.com 99.90 +998 customer998@example.com 99.80 +997 customer997@example.com 99.70 +``` + +With a thousand rows it works. With a million rows we are back where we started: + +```text +Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32768 bytes) +``` + +This time `fgetcsv` doesn't help. The script needs 624Mb for a 62Mb file, ten times its size, and it grows with every row. +To do it right we would have to cut the file into sorted chunks on disk and merge them back. That's a lot of code for "sort a file". + +## The same thing with Flow + +Flow needs PHP 8.3 or newer. + +```bash +composer require flow-php/etl flow-php/etl-adapter-csv +``` + +```php +read(from_csv(__DIR__ . '/orders.csv')) + ->sortBy(ref('amount')->desc()) + ->write(to_csv(__DIR__ . '/orders-sorted.csv')->saveMode(overwrite())) + ->run(); + +data_frame() + ->read(from_csv(__DIR__ . '/orders-sorted.csv')) + ->select('id', 'email', 'amount') + ->limit(3) + ->write(to_output(truncate: false)) + ->run(); +``` + +```text output ++-----+-------------------------+-----------+ +| id | email | amount | ++-----+-------------------------+-----------+ +| 999 | customer999@example.com | 99.900000 | +| 998 | customer998@example.com | 99.800000 | +| 997 | customer997@example.com | 99.700000 | ++-----+-------------------------+-----------+ +3 rows +``` + +[`from_csv`](/documentation/dsl/csv/from-csv) reads the file row by row, detects the separator and the type of every column, so `amount` is already a float. +[`sortBy`](/documentation/components/core/sort) keeps as many rows in memory as the limit allows and moves the rest to disk, so the script never needs more than it has. +The second pipeline is there only to show us the first three rows of the result. + +The revenue report from the beginning is the same shape: + +```php +read(from_csv(__DIR__ . '/orders.csv')) + ->groupBy([ref('country')]) + ->aggregate(sum(ref('amount'))) + ->sortBy(ref('amount_sum')->desc()) + ->write(to_output(truncate: false)) + ->run(); +``` + +```text output ++---------+--------------+ +| country | amount_sum | ++---------+--------------+ +| GB | 10030.000000 | +| FR | 10010.000000 | +| DE | 9990.000000 | +| US | 9970.000000 | +| PL | 9950.000000 | ++---------+--------------+ +5 rows +``` + +## How much memory does a large CSV file take in PHP + +PHP 8.3, `memory_limit=128M`, a million rows, 62Mb: + +| Task | Code | Peak memory | Time | +|---------------------|-------------------------------------|--------------------------|------| +| Revenue per country | `file()` | fatal error, needs 172Mb | - | +| Revenue per country | `fgetcsv` loop | 2Mb | 1.6s | +| Revenue per country | Flow | 44Mb | 4.9s | +| Revenue per country | Flow with the `flow_php` extension | 16Mb | 0.6s | +| Sort by amount | `fgetcsv` and `usort` | fatal error, needs 624Mb | - | +| Sort by amount | Flow | 98Mb | 7.4s | +| Sort by amount | Flow with the `flow_php` extension | 18Mb | 1.0s | + +The numbers that matter are the ones that don't change. With three million rows and a 189Mb file the plain sort needs 1942Mb, and Flow still takes 97Mb, or 20Mb with the extension. + +[flow_php](/documentation/components/extensions/flow-php-ext) is an optional PHP extension. The scripts stay the same, without a single change. + +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); +``` diff --git a/web/landing/content/guides/read-large-json-file-in-php.md b/web/landing/content/guides/read-large-json-file-in-php.md new file mode 100644 index 0000000000..68d35d56d5 --- /dev/null +++ b/web/landing/content/guides/read-large-json-file-in-php.md @@ -0,0 +1,162 @@ +--- +seo_title: Read a large JSON file in PHP without running out of memory +seo_description: 'json_decode needs the whole file in memory, so a big JSON file ends with "Allowed memory size exhausted". Why it happens, and how to read a 110Mb JSON file in PHP with 22Mb.' +group: Reading files +problem: 'json_decode() needs 778Mb for a 110Mb file' +proof_label: 'Reading a 110Mb file' +proof_before: '778Mb' +proof_after: '22Mb' +published: '2026-11-18' +updated: '2026-11-18' +--- + +# Read a large JSON file in PHP without running out of memory + +Let's say a partner sends us their orders as one JSON file: a million orders, 110Mb. +We need the revenue per country, and our PHP process runs with the default `memory_limit` of 128Mb. + +## The file + +First we need a file to work with, so let's generate one. +Set `$rows` to `1_000_000` to get the 110Mb version. + +```php + $id, + 'email' => "customer{$id}@example.com", + 'country' => ['PL', 'US', 'DE', 'FR', 'GB'][$id % 5], + 'amount' => ($id % 1000) / 10, + 'created_at' => gmdate('Y-m-d H:i:s', 1_700_000_000 + $id * 60), + ]) . ($id < $rows ? ",\n" : "\n")); +} + +fwrite($file, "]\n"); +fclose($file); + +echo "orders.json: {$rows} orders\n"; +``` + +```text output +orders.json: 1000 orders +``` + +## Read a JSON file with json_decode + +There is one way to read JSON in PHP that everybody knows: `file_get_contents` and `json_decode`. + +```php + $total) { + printf("%s %.2f\n", $country, $total); +} +``` + +```text output +GB 10030.00 +FR 10010.00 +DE 9990.00 +US 9970.00 +PL 9950.00 +``` + +With a thousand orders it works. With a million orders it ends like this: + +```text +Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes) +``` + +## Why json_decode ends with "Allowed memory size exhausted" + +`json_decode` can't read a part of a file. It needs the whole document as one string, and then it builds a PHP array for every order in it. +For our file that is 778Mb, seven times the size of the file. + +With a CSV file we could switch to `fgetcsv` and read it row by row. There is nothing like that for JSON. +PHP has no function that reads a JSON file one element at a time, so we would have to write our own parser. + +## Read a large JSON file with Flow + +Flow needs PHP 8.3 or newer. + +```bash +composer require flow-php/etl flow-php/etl-adapter-json +``` + +```php +read(from_json(__DIR__ . '/orders.json')) + ->groupBy([ref('country')]) + ->aggregate(sum(ref('amount'))) + ->sortBy(ref('amount_sum')->desc()) + ->write(to_output(truncate: false)) + ->run(); +``` + +```text output ++---------+--------------+ +| country | amount_sum | ++---------+--------------+ +| GB | 10030.000000 | +| FR | 10010.000000 | +| DE | 9990.000000 | +| US | 9970.000000 | +| PL | 9950.000000 | ++---------+--------------+ +5 rows +``` + +[`from_json`](/documentation/dsl/json/from-json) reads the file one order at a time, so it doesn't matter how big the file is. +`groupBy` with [`sum`](/documentation/dsl/core/sum) adds up the amounts per country, and `sortBy` puts the biggest one first. + +## How much memory does a large JSON file take in PHP + +PHP 8.3, `memory_limit=128M`: + +| Orders | File size | Code | Peak memory | Time | +|-----------|-----------|------------------------------------|---------------------------|------| +| 1,000,000 | 110Mb | `json_decode` | fatal error, needs 778Mb | - | +| 1,000,000 | 110Mb | Flow | 22Mb | 2.6s | +| 1,000,000 | 110Mb | Flow with the `flow_php` extension | 20Mb | 1.0s | +| 3,000,000 | 335Mb | `json_decode` | fatal error, needs 2353Mb | - | +| 3,000,000 | 335Mb | Flow | 22Mb | 6.8s | +| 3,000,000 | 335Mb | Flow with the `flow_php` extension | 20Mb | 2.2s | + +Three times more orders cost Flow nothing. They cost `json_decode` 1575Mb. + +[flow_php](/documentation/components/extensions/flow-php-ext) is an optional PHP extension. The script stays the same, without a single change. + +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); +``` diff --git a/web/landing/content/guides/stream-large-csv-download-in-symfony.md b/web/landing/content/guides/stream-large-csv-download-in-symfony.md new file mode 100644 index 0000000000..d30fcfd824 --- /dev/null +++ b/web/landing/content/guides/stream-large-csv-download-in-symfony.md @@ -0,0 +1,272 @@ +--- +seo_title: 'Export a large CSV file in PHP: stream the download in Symfony' +seo_description: 'A Symfony StreamedResponse still loads the whole query result and runs out of memory. How to stream a million rows as CSV, JSON, XML or Parquet in 20Mb.' +group: Writing files +problem: 'StreamedResponse still runs out of memory' +proof_label: 'A million orders as a download' +proof_before: '91Mb' +proof_after: '20Mb' +published: '2026-11-18' +updated: '2026-11-18' +--- + +# Stream a large CSV download in Symfony without running out of memory + +Let's say our application has a "Download orders" button. +There are a million orders in MySQL, and our PHP process runs with the default `memory_limit` of 128Mb. + +> The controllers in this guide need a Symfony application and a database, so they don't run in the playground. Run them in your project. + +## Export a CSV file with a Symfony StreamedResponse + +Symfony has a response made for this. We don't build the file first. We send every order to the browser as soon as we read it. + +```php ignore +database->executeQuery('SELECT id, email, country, amount, created_at FROM orders ORDER BY id'); + + while ($order = $orders->fetchAssociative()) { + fputcsv($output, $order, escape: ''); + } + }, 200, [ + 'Content-Type' => 'text/csv', + 'Content-Disposition' => 'attachment; filename="orders.csv"', + ]); + } +} +``` + +It looks right. Nothing is collected in an array, and every order goes straight to the output. + +## Why StreamedResponse still ends with "Allowed memory size exhausted" + +Let's look at how much memory that controller takes: + +| Orders | Peak memory | +|-----------|-------------| +| 500,000 | 52Mb | +| 1,000,000 | 91Mb | +| 2,000,000 | fatal error | + +The more orders we have, the more memory it takes, and at two million it ends with: + +```text +Fatal error: Allowed memory size of 134217728 bytes exhausted +``` + +The response is streamed, but the query is not. The MySQL driver reads the whole result into memory before we get the first order from it. +So the download works on our machine, works for the first year in production, and then one day it stops. + +## Then somebody asks for JSON or XML + +The next request is always the same: "can we get it as JSON?". +There is nothing to reuse from the CSV controller. Every format is its own code: + +```php ignore tab="JSON" +return new StreamedResponse(function (): void { + $orders = $this->database->executeQuery('SELECT id, email, country, amount, created_at FROM orders ORDER BY id'); + $first = true; + + echo '['; + + while ($order = $orders->fetchAssociative()) { + $order['amount'] = (float) $order['amount']; + + echo $first ? '' : ',', json_encode($order, JSON_THROW_ON_ERROR); + $first = false; + } + + echo ']'; +}, 200, [ + 'Content-Type' => 'application/json', + 'Content-Disposition' => 'attachment; filename="orders.json"', +]); +``` + +```php ignore tab="XML" +return new StreamedResponse(function (): void { + $orders = $this->database->executeQuery('SELECT id, email, country, amount, created_at FROM orders ORDER BY id'); + + $xml = new XMLWriter(); + $xml->openUri('php://output'); + $xml->startDocument('1.0', 'UTF-8'); + $xml->startElement('rows'); + + while ($order = $orders->fetchAssociative()) { + $xml->startElement('row'); + + foreach ($order as $column => $value) { + $xml->writeElement($column, (string) $value); + } + + $xml->endElement(); + $xml->flush(); + } + + $xml->endElement(); + $xml->endDocument(); + $xml->flush(); +}, 200, [ + 'Content-Type' => 'application/xml', + 'Content-Disposition' => 'attachment; filename="orders.xml"', +]); +``` + +For JSON we write the brackets and the commas ourselves, and we cast the amount, because the database gives it to us as a string. +For XML we need `XMLWriter`, and we have to flush it after every order, or the whole document waits in memory. +And both of them still read the whole query result first, so they take the same 91Mb. + +## Export and stream the download with Flow + +Flow needs PHP 8.3 or newer. + +```bash +composer require flow-php/etl flow-php/etl-adapter-doctrine flow-php/symfony-http-foundation-bridge +``` + +```php ignore +database, + $this->database->createQueryBuilder() + ->select('id', 'email', 'country', 'amount', 'created_at') + ->from('orders'), + pagination_key_set(pagination_key_asc('id')), + )->withSchema(schema( + int_schema('id'), + str_schema('email'), + str_schema('country'), + float_schema('amount'), + datetime_schema('created_at'), + )); + + return http_stream_open($orders) + ->transform( + mask_columns(['email']), + with_column('created_at', ref('created_at')->dateFormat('Y-m-d')), + ) + ->as('orders.csv') + ->streamedResponse(http_csv_output()); + } +} +``` + +```text +id,email,country,amount,created_at +1,******,US,0.1,2023-11-14 +2,******,DE,0.2,2023-11-14 +3,******,FR,0.3,2023-11-14 +``` + +[`from_dbal_key_set_qb`](/documentation/dsl/doctrine/from-dbal-key-set-qb) doesn't ask the database for everything at once. It reads the table page by page, and every page starts where the previous one ended. +The MySQL driver can't tell Flow the type of a column in a query result, so we name the columns and their types with `withSchema`. + +## Mask and format the data on the way out + +The file goes to somebody outside of our team, so we don't want the emails in it, and nobody needs the time of the order down to the second. + +In the controllers written by hand that is three more lines in the loop, in every one of the three controllers: + +```php ignore +$order['email'] = '******'; +$order['amount'] = (float) $order['amount']; +$order['created_at'] = (new DateTimeImmutable($order['created_at']))->format('Y-m-d'); +``` + +With Flow it is written once, and that is what [`transform`](/documentation/components/bridges/symfony-http-foundation-bridge) is for. [`mask_columns`](/documentation/dsl/core/mask-columns) replaces every email with `******`, and `dateFormat` leaves only the date. +We didn't touch the query, and we didn't write a loop. + +## Change the format in one line + +Now the JSON and the XML version. With Flow it's the last two lines of the controller: + +```php ignore tab="CSV" +->as('orders.csv') +->streamedResponse(http_csv_output()); +``` + +```php ignore tab="JSON" +->as('orders.json') +->streamedResponse(http_json_output()); +``` + +```php ignore tab="XML" +->as('orders.xml') +->streamedResponse(http_xml_output()); +``` + +```php ignore tab="Parquet" +->as('orders.parquet') +->streamedResponse(http_parquet_output()); +``` + +## How much memory does a streamed download take in Symfony + +PHP 8.3, `memory_limit=128M`, a million orders in MySQL. Every controller masks the emails and formats the dates, so they all send the same file: + +| Format | `StreamedResponse` by hand | Flow | Flow with the `flow_php` extension | +|---------|----------------------------|-------------|------------------------------------| +| CSV | 91Mb, 3.7s | 20Mb, 6.5s | 20Mb, 4.5s | +| JSON | 91Mb, 4.5s | 20Mb, 6.7s | 20Mb, 4.2s | +| XML | 91Mb, 4.9s | 20Mb, 7.0s | 20Mb, 5.3s | +| Parquet | - | 42Mb, 10.2s | 20Mb, 4.4s | + +With the extension Flow is as fast as the controllers written by hand for JSON, and close to them for CSV and XML. Without it they are faster. +But they are three different pieces of code, and their memory grows with the table. +The Flow controller is one piece of code with one line changed, and with half of the orders or with all of them it takes the same 20Mb. + +> Flow is slower here than it should be. The keyset reader does more work for every row than it needs to, and there is an open issue for it: [flow-php/flow#2748](https://github.com/flow-php/flow/issues/2748). + +[flow_php](/documentation/components/extensions/flow-php-ext) is an optional PHP extension. The controller stays the same, without a single change. diff --git a/web/landing/src/Flow/Website/Controller/GuidesController.php b/web/landing/src/Flow/Website/Controller/GuidesController.php new file mode 100644 index 0000000000..e6790d1080 --- /dev/null +++ b/web/landing/src/Flow/Website/Controller/GuidesController.php @@ -0,0 +1,96 @@ + 1, + 'Writing files' => 2, + 'Importing data' => 3, + 'Search' => 4, + ]; + + public function __construct( + #[Autowire(service: 'guides.pages')] + private readonly Pages $guides, + ) {} + + #[Route('/guides/{slug}', name: 'guides_guide')] + public function guide(string $slug, CardGenerator $socialCards): Response + { + try { + $guide = $this->guides->get($slug); + } catch (RuntimeException) { + throw $this->createNotFoundException(); + } + + $others = array_filter($this->guides->all(), static fn(Page $other): bool => $other->path !== $slug); + + usort( + $others, + static fn(Page $left, Page $right): int => ( + [$left->group() !== $guide->group(), $left->path] <=> [ + $right->group() !== $guide->group(), + $right->path, + ] + ), + ); + + return $this->render('guides/guide.html.twig', [ + 'guide' => $guide, + 'slug' => $slug, + 'social_image' => $socialCards->generate($guide, $slug), + 'related' => array_slice($others, offset: 0, length: 3), + ]); + } + + #[Route('/guides', name: 'guides', options: ['sitemap' => true])] + public function index(): Response + { + $groups = []; + $featured = []; + + foreach ($this->guides->all() as $guide) { + $groups[$guide->group()][$guide->path] = $guide; + + if ($guide->card()['featured']) { + $featured[$guide->path] = $guide; + } + } + + uksort( + $groups, + static fn(string $left, string $right): int => ( + [self::GROUP_POSITIONS[$left] ?? PHP_INT_MAX, $left] <=> [ + self::GROUP_POSITIONS[$right] ?? PHP_INT_MAX, + $right, + ] + ), + ); + + foreach (array_keys($groups) as $group) { + ksort($groups[$group]); + } + + return $this->render('guides/index.html.twig', ['groups' => $groups, 'featured' => $featured]); + } +} diff --git a/web/landing/src/Flow/Website/EventListener/SitemapSubscriber.php b/web/landing/src/Flow/Website/EventListener/SitemapSubscriber.php index a8f4b627e1..b84516e994 100644 --- a/web/landing/src/Flow/Website/EventListener/SitemapSubscriber.php +++ b/web/landing/src/Flow/Website/EventListener/SitemapSubscriber.php @@ -10,6 +10,7 @@ use Flow\Website\Service\Examples; use Presta\SitemapBundle\Event\SitemapPopulateEvent; use Presta\SitemapBundle\Sitemap\Url\UrlConcrete; +use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; @@ -22,6 +23,8 @@ public function __construct( private Posts $posts, private DSLDefinitions $dslDefinitions, private Pages $pages, + #[Autowire(service: 'guides.pages')] + private Pages $guides, ) {} public static function getSubscribedEvents() @@ -36,6 +39,7 @@ public function populate(SitemapPopulateEvent $event): void $this->populateExamples($event); $this->populateBlogPosts($event); $this->populateDocumentation($event); + $this->populateGuides($event); } private function populateBlogPosts(SitemapPopulateEvent $event): void @@ -138,4 +142,21 @@ private function populateExamples(SitemapPopulateEvent $event): void } } } + + private function populateGuides(SitemapPopulateEvent $event): void + { + foreach ($this->guides->all() as $guide) { + $event->getUrlContainer()->addUrl( + new UrlConcrete( + $event->getUrlGenerator()->generate( + 'guides_guide', + ['slug' => $guide->path], + UrlGeneratorInterface::ABSOLUTE_URL, + ), + changefreq: 'weekly', + ), + 'guides', + ); + } + } } diff --git a/web/landing/src/Flow/Website/Model/Documentation/Page.php b/web/landing/src/Flow/Website/Model/Documentation/Page.php index 92f60edf2b..16e08a586b 100644 --- a/web/landing/src/Flow/Website/Model/Documentation/Page.php +++ b/web/landing/src/Flow/Website/Model/Documentation/Page.php @@ -20,6 +20,22 @@ public function __construct( public string $content, ) {} + /** + * @return array{problem: ?string, proof_label: ?string, proof_before: ?string, proof_after: ?string, featured: bool} + */ + public function card(): array + { + $frontMatter = $this->frontMatter(); + + return [ + 'problem' => type_union(type_string(), type_null())->assert($frontMatter['problem'] ?? null), + 'proof_label' => type_union(type_string(), type_null())->assert($frontMatter['proof_label'] ?? null), + 'proof_before' => type_union(type_string(), type_null())->assert($frontMatter['proof_before'] ?? null), + 'proof_after' => type_union(type_string(), type_null())->assert($frontMatter['proof_after'] ?? null), + 'featured' => ($frontMatter['featured'] ?? false) === true, + ]; + } + public function description(): ?string { $frontMatter = $this->frontMatter(); @@ -34,6 +50,11 @@ public function editOnGitHubUrl(): string return 'https://github.com/flow-php/flow/edit/1.x/documentation/' . ltrim($this->path, '/'); } + public function group(): string + { + return type_string()->assert($this->frontMatter()['group'] ?? null); + } + public function package(): ?string { $frontMatter = $this->frontMatter(); @@ -41,6 +62,11 @@ public function package(): ?string return type_union(type_string(), type_null())->assert($frontMatter['package'] ?? null); } + public function published(): string + { + return type_string()->assert($this->frontMatter()['published'] ?? null); + } + public function title(): ?string { $frontMatter = $this->frontMatter(); @@ -48,6 +74,11 @@ public function title(): ?string return type_union(type_string(), type_null())->assert($frontMatter['seo_title'] ?? null) ?? 'Documentation'; } + public function updated(): string + { + return type_string()->assert($this->frontMatter()['updated'] ?? null); + } + /** * @return array */ diff --git a/web/landing/src/Flow/Website/Service/Markdown/FlowCodeTabsRenderer.php b/web/landing/src/Flow/Website/Service/Markdown/FlowCodeTabsRenderer.php new file mode 100644 index 0000000000..e27c7357fc --- /dev/null +++ b/web/landing/src/Flow/Website/Service/Markdown/FlowCodeTabsRenderer.php @@ -0,0 +1,89 @@ +getDocument()->walker(); + $groups = []; + $group = -1; + + while ($walkEvent = $walker->next()) { + $node = $walkEvent->getNode(); + + if (!$walkEvent->isEntering() || !$node instanceof FencedCode || $this->tabName($node) === null) { + continue; + } + + if ($this->tabName($node->previous()) === null) { + $group++; + } + + $groups[$group][] = $node; + } + + foreach ($groups as $blocks) { + $tabs = ''; + + foreach ($blocks as $block) { + $name = htmlspecialchars((string) $this->tabName($block), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); + $tabs .= + ''; + + $block->insertBefore($this->html( + '

' + . $name + . '

', + )); + $block->insertAfter($this->html('
')); + } + + $blocks[0] + ->previous() + ?->insertBefore($this->html( + '
' + . $tabs + . '
', + )); + $blocks[array_key_last($blocks)]->next()?->insertAfter($this->html('
')); + } + } + + private function html(string $literal): HtmlBlock + { + $block = new HtmlBlock(HtmlBlock::TYPE_6_BLOCK_ELEMENT); + $block->setLiteral($literal); + + return $block; + } + + private function tabName(?Node $node): ?string + { + $name = []; + + if (!$node instanceof FencedCode || preg_match('/\btab="([^"]+)"/', (string) $node->getInfo(), $name) !== 1) { + return null; + } + + return $name[1]; + } +} diff --git a/web/landing/src/Flow/Website/Service/Markdown/LeagueCommonMarkConverterFactory.php b/web/landing/src/Flow/Website/Service/Markdown/LeagueCommonMarkConverterFactory.php index 4c02ddfde5..562f84a6be 100644 --- a/web/landing/src/Flow/Website/Service/Markdown/LeagueCommonMarkConverterFactory.php +++ b/web/landing/src/Flow/Website/Service/Markdown/LeagueCommonMarkConverterFactory.php @@ -87,7 +87,8 @@ public function __invoke(): CommonMarkConverter ) ->addEventListener(DocumentParsedEvent::class, new FlowManifestRenderer($this->manifest)) ->addEventListener(DocumentParsedEvent::class, new FlowPackageNavRenderer($this->manifest)) - ->addEventListener(DocumentParsedEvent::class, new FlowDocLinkRenderer()); + ->addEventListener(DocumentParsedEvent::class, new FlowDocLinkRenderer()) + ->addEventListener(DocumentParsedEvent::class, new FlowCodeTabsRenderer()); return $converter; } diff --git a/web/landing/src/Flow/Website/SocialCard/Guides/CardGenerator.php b/web/landing/src/Flow/Website/SocialCard/Guides/CardGenerator.php new file mode 100644 index 0000000000..5bd97a6021 --- /dev/null +++ b/web/landing/src/Flow/Website/SocialCard/Guides/CardGenerator.php @@ -0,0 +1,71 @@ +painter->canvas(); + $card = $guide->card(); + + $this->painter->drawElephant($canvas); + $this->painter->drawEyebrow($canvas, section: 'GUIDE'); + $this->painter->drawDescription( + $canvas, + (string) $card['problem'], + $this->painter->drawTitle($canvas, (string) $guide->title()), + ); + + if ($card['proof_after'] !== null) { + $this->painter->drawFooter( + $canvas, + $card['proof_before'] === null + ? $card['proof_after'] + : $card['proof_before'] . ' to ' . $card['proof_after'], + $card['proof_label'], + primaryColor: CardPainter::ORANGE, + ); + } + + $this->painter->drawAccentBar($canvas); + + $path = $this->publicDir . $this->relativePath($slug); + + if ( + !is_dir(dirname($path)) + && !mkdir(dirname($path), permissions: 0o755, recursive: true) + && !is_dir(dirname($path)) + ) { + throw new RuntimeException('Failed to create directory: ' . dirname($path)); + } + + if (imagepng($canvas, $path) === false) { + throw new RuntimeException('Failed to write social card: ' . $path); + } + + return $this->relativePath($slug); + } + + public function relativePath(string $slug): string + { + return sprintf('/images/guides/social/%s.png', $slug); + } +} diff --git a/web/landing/src/Flow/Website/StaticSourceProvider/GuidesProvider.php b/web/landing/src/Flow/Website/StaticSourceProvider/GuidesProvider.php new file mode 100644 index 0000000000..2d41875f2a --- /dev/null +++ b/web/landing/src/Flow/Website/StaticSourceProvider/GuidesProvider.php @@ -0,0 +1,29 @@ +guides->all() as $guide) { + $sources[] = new Source('guides_guide', ['slug' => $guide->path]); + } + + return $sources; + } +} diff --git a/web/landing/templates/base.html.twig b/web/landing/templates/base.html.twig index 95b3836ada..86cda8bb37 100644 --- a/web/landing/templates/base.html.twig +++ b/web/landing/templates/base.html.twig @@ -30,6 +30,7 @@ + {% block social_image %} diff --git a/web/landing/templates/guides/guide.html.twig b/web/landing/templates/guides/guide.html.twig new file mode 100644 index 0000000000..c508c73cef --- /dev/null +++ b/web/landing/templates/guides/guide.html.twig @@ -0,0 +1,93 @@ +{% extends 'base.html.twig' %} + +{%- block title -%} + {{ guide.title }} | Flow PHP +{%- endblock -%} + +{%- block description -%} + {{ guide.description }} +{%- endblock -%} + +{%- block og_type -%}article{%- endblock -%} + +{% block social_image %} + + + + + + +{% endblock %} + +{%- block hero -%}{%- endblock -%} + +{%- block contributors -%}{%- endblock -%} + +{% block main %} +
+ + +

+ Last updated +

+ +
+ + + {{ guide.content|markdown_to_html }} +
+ + + +

+ Found a typo or an outdated section? + + Edit this guide on GitHub + +

+
+ + +{% endblock %} diff --git a/web/landing/templates/guides/index.html.twig b/web/landing/templates/guides/index.html.twig new file mode 100644 index 0000000000..34e83aaa77 --- /dev/null +++ b/web/landing/templates/guides/index.html.twig @@ -0,0 +1,123 @@ +{% extends 'base.html.twig' %} + +{%- block title -%} + Data processing in PHP: guides with code that runs | Flow PHP +{%- endblock -%} + +{%- block description -%} + Real data problems in PHP, one per page, with code that runs: large CSV, JSON and Excel files, database imports and exports, REST APIs and search. +{%- endblock -%} + +{%- block hero -%}{%- endblock -%} + +{% block main %} +
+
+
+ + + Guides + +

Data processing in PHP

+

+ One problem per page, with code that runs. + Each guide shows the plain PHP way first, then the same thing with Flow. +

+
+ +
    +
  • + + Complete scripts, ready to copy +
  • +
  • + + Plain PHP first, then Flow +
  • +
  • + + Memory and time, measured +
  • +
+
+ + {% for slug, guide in featured %} + {% set guideUrl = path('guides_guide', {slug: slug}) %} +
+
+ + + Start here + +

{{ guide.card.problem }}

+

+ + {{ guide.title }} + +

+

{{ guide.description }}

+ + Read the guide + +
+ {% if guide.card.proof_after %} +
+

{{ guide.card.proof_label }}

+

+ {% if guide.card.proof_before %} + {{ guide.card.proof_before }} + + {% endif %} + {{ guide.card.proof_after }} +

+
+ {% endif %} +
+ {% endfor %} + + {% for group, guides in groups %} +
+

{{ group }}

+ + {{ guides|length }} +
+ +
+ {% for slug, guide in guides %} + {% set guideUrl = path('guides_guide', {slug: slug}) %} +
+

{{ guide.card.problem }}

+

+ + {{ guide.title }} + +

+

+ {{ guide.description }} +

+ {% if guide.card.proof_after %} +

+ {% if guide.card.proof_before %} + {{ guide.card.proof_before }} + + {% endif %} + {{ guide.card.proof_after }} + {{ guide.card.proof_label }} +

+ {% endif %} +
+ + Read the guide + + +
+
+ {% endfor %} +
+ {% endfor %} +
+{% endblock %} diff --git a/web/landing/templates/partials/footer.html.twig b/web/landing/templates/partials/footer.html.twig index 11c331aed7..9ba41db159 100644 --- a/web/landing/templates/partials/footer.html.twig +++ b/web/landing/templates/partials/footer.html.twig @@ -15,6 +15,7 @@

Product