Stream a Drupal CSV export without the memory hit
Last month a client asked for a "quick CSV of all articles" on a Drupal 11 site with about 40,000 nodes. My first version built an array of rows, joined them into a string and returned a normal Response. It worked on my laptop and died with a memory-limit error on the server. The fix is to never hold the whole export in memory: a generator produces rows, and StreamedResponse writes them to the client as they appear.
Step 1: a generator that pages through nodes
The trick is to page by nid rather than by offset. With range($offset, $limit) every page gets slower as the offset grows, and rows shift if someone publishes a node mid-export. Filtering on nid > $last keeps each query cheap and stable. After each chunk I call resetCache() on the storage, because Drupal's static entity cache would otherwise keep every loaded node alive and defeat the whole exercise.
<?php
namespace Drupal\my_export\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\HeaderUtils;
use Symfony\Component\HttpFoundation\StreamedResponse;
class ArticleCsvController extends ControllerBase implements ContainerInjectionInterface {
private const CHUNK = 200;
public function __construct(private readonly EntityTypeManagerInterface $etm) {}
public static function create(ContainerInterface $container): static {
return new static($container->get('entity_type.manager'));
}
/**
* Yields one CSV row at a time, loading nodes in small chunks.
*/
private function rows(): \Generator {
$storage = $this->etm->getStorage('node');
$last = 0;
while (TRUE) {
$ids = $storage->getQuery()
->accessCheck(TRUE)
->condition('type', 'article')
->condition('nid', $last, '>')
->sort('nid')
->range(0, self::CHUNK)
->execute();
if (!$ids) {
return;
}
foreach ($storage->loadMultiple($ids) as $node) {
yield [
$node->id(),
$node->label(),
$node->getOwner()->getDisplayName(),
date('c', (int) $node->getCreatedTime()),
];
}
$last = (int) max($ids);
$storage->resetCache($ids);
}
}
Step 2: stream it, and defuse the CSV
The response callback opens php://output and writes each yielded row with fputcsv(). Note the explicit '' escape argument: per the PHP manual, relying on the default $escape value has been deprecated since PHP 8.4, and an empty string gives RFC 4180 compliant output.
The neutralize() helper matters more than it looks. Node titles are user-controlled, and a title like =HYPERLINK(...) becomes a live formula when someone opens the file in Excel. Prefixing a quote on cells that start with =, +, -, @, tab or carriage return is the usual mitigation.
public function download(): StreamedResponse {
$response = new StreamedResponse(function (): void {
$out = fopen('php://output', 'w');
fputcsv($out, ['nid', 'title', 'author', 'created'], ',', '"', '');
foreach ($this->rows() as $row) {
fputcsv($out, array_map($this->neutralize(...), $row), ',', '"', '');
flush();
}
fclose($out);
});
$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
$response->headers->set('Content-Disposition', HeaderUtils::makeDisposition(
HeaderUtils::DISPOSITION_ATTACHMENT,
'articles.csv'
));
$response->headers->set('Cache-Control', 'no-store');
$response->headers->set('X-Accel-Buffering', 'no');
return $response;
}
/**
* Stops spreadsheet apps from running user text as a formula.
*/
private function neutralize(mixed $value): mixed {
if (is_string($value) && $value !== '' && str_contains("=+-@\t\r", $value[0])) {
return "'" . $value;
}
return $value;
}
}
Step 3: the route
Gate it behind a permission. The generator already runs with accessCheck(TRUE), so the export only contains nodes the current user may view.
my_export.articles_csv:
path: '/admin/content/articles.csv'
defaults:
_controller: '\Drupal\my_export\Controller\ArticleCsvController::download'
requirements:
_permission: 'access content overview'
A few gotchas. Streaming only helps if nothing upstream buffers: I send X-Accel-Buffering: no for nginx, but your proxy or CDN may need its own setting. Because headers go out before the first row, you cannot switch to an error page halfway through; if a query fails you get a truncated file, so log failures inside the callback. And for exports that run longer than a request should live, skip streaming and use the Queue or Batch API to build a file in the background instead. For anything that fits in one request, though, this pattern keeps memory flat at roughly one chunk of nodes, whether you export 400 rows or 400,000. I traced the loop by hand rather than running it, so test it against your own content types before trusting it.