Lewati ke konten
PHP Ecosystem
Explore

Configuration

Konten ini belum tersedia dalam bahasa Anda.

CsvExporter is configured like a Yii grid: a data source, a list of columns, and options for the files it writes. export() returns an ExportResult that owns the generated files.

Set dataProvider or query. When both are configured, the provider supplies the rows, keys and label context.

OptionDefaultPurpose
dataProvidernullA yii\data\DataProviderInterface. Its pagination sets batches.
querynullA yii\db\QueryInterface. Used when no provider is configured.
batchSize100Rows fetched per batch. Applies to query only.

The exporter reads one batch at a time. Query drivers can buffer rows, and an ArrayDataProvider already holds its inputs in memory. Use a deterministic order for query and paginated exports. Run against a stable snapshot if concurrent updates could change which rows fall on each page.

With a data provider, the pagination page size is the batch size. The exporter works on a copy of the provider, starts at page zero and leaves the caller’s provider untouched. Disabling pagination disables batching. A custom provider with pagination must return an independent pagination object when cloned.

With a query, the exporter uses batch() when the query class has it, as yii\db\Query and yii\db\ActiveQuery do. Otherwise it wraps the query in an ActiveDataProvider whose page size is batchSize.

Each entry of columns is a string, a configuration array or a Column instance. Without columns, the schema is inferred from the first row and every inferred name is used literally.

'columns' => [
['class' => SerialColumn::class],
'name',
'price:decimal:Price',
[
'attribute' => 'status',
'header' => 'State',
'value' => static fn (array $model): string => strtoupper($model['status']),
],
],
  • A string uses the attribute, attribute:format or attribute:format:label shorthand.
  • An array without class configures a DataColumn. attribute names the value to read, value replaces it with another attribute name or a callable, format selects the Yii formatter format and label sets the header.
  • content is a callable that renders the whole cell and bypasses the formatter.
  • header and footer set literal cell text. visible => false removes the column.
  • SerialColumn renders a row number that keeps counting across batches and files.

Callables receive ($model, $key, $index, $column). $key is the provider key; a yii\db\Query without indexBy() passes the global row index. DataColumn formats with raw by default, and a null value renders nullDisplay without reaching the formatter. The header of a DataColumn falls back to the model’s attribute label, then to a humanized attribute name.

OptionDefaultPurpose
showHeadertrueWrites the header row at the top of every file.
showFooterfalseWrites the footer row at the bottom of every file.
emptyCell''Text for cells with no content, such as an unset footer.
nullDisplay''Text for null data values.
formatterappA yii\i18n\Formatter or its configuration array.

maxEntriesPerFile limits the rows in one file, counting the header and footer rows. null or 0 disables splitting. A limit that cannot fit one data row is rejected.

When an export produces more than one file, the result is a single archive. resultConfig configures the ExportResult:

OptionDefaultPurpose
basePath@runtime/csv-exportParent of the private export directory.
fileBaseNamedataBase name of the files: data-001.csv, data-002.csv, data.zip.
forceArchivefalseArchives the result even when it holds a single file.
archivernullCallable (array $files, string $dirName): string.
classExportResultA subclass of ExportResult.

The built-in archiver needs the zip extension. A custom archiver must return a readable file directly inside $dirName.

csvFileConfig configures every CsvFile the export creates.

OptionDefaultPurpose
cellDelimiter,One byte between cells.
enclosure"One byte around every cell, or an empty string for no quoting.
rowDelimiter"\r\n""\r\n", "\n" or "\r" between records.
encodingUTF-8UTF-8, UTF-16LE or UTF-16BE.
writeBomfalsetrue writes the BOM of encoding; a string is written as is.
spreadsheetSafefalsePrefixes formula-like text with an apostrophe.

Records are joined by rowDelimiter, so the file has no line break after the last record. Cells accept scalar values, null and objects implementing Stringable.

With no enclosure, fields containing the delimiter or a line break are rejected. Keep the default quoted dialect for arbitrary text.

The default output preserves text. For UTF-8 text intended for spreadsheet import, spreadsheetSafe prefixes formula-like text with an apostrophe. It changes strings only: the string '-42' is prefixed and the integer -42 is not. This changes the exported text, including headers and footers. Verify the chosen import behavior in the target spreadsheet.

With UTF-16LE or UTF-16BE the writer converts UTF-8 input before writing each record. A known BOM supplied as bytes must match the output encoding.

Each export writes into a private child of resultConfig.basePath. Configure the parent and every destination with trusted application paths; do not build them from user input. The result removes its directory when it is deleted, after send() completes, and when the object is destroyed, so keep the result alive until delivery finishes.

Call ExportResult::purgeExpired($basePath, $ageInSeconds) from a maintenance task to clear old, unlocked workspaces left behind by interrupted processes. Use the same parent as the exports and choose the retention for the application. Live exports hold a lease and are ignored.

Continue with usage examples.

Back to documentation