Ir al contenido
PHP Ecosystem
Explore

Usage examples

Esta página aún no está disponible en tu idioma.

The examples assume a Yii application and an Item ActiveRecord class. Options are described in configuration.

The pagination page size is the export batch size.

<?php
use yii2\extensions\csvexport\CsvExporter;
use yii\data\ActiveDataProvider;
$exporter = new CsvExporter(
[
'dataProvider' => new ActiveDataProvider([
'query' => Item::find()->orderBy('id'),
'pagination' => [
'pageSize' => 100, // export batch size
],
]),
],
);
$exporter->export()->saveAs('/path/to/file.csv');

If pagination is disabled in the data provider, no batch processing is performed.

<?php
use yii2\extensions\csvexport\CsvExporter;
$exporter = new CsvExporter(
[
'query' => Item::find()->orderBy('id'),
'batchSize' => 200, // export batch size
],
);
$exporter->export()->saveAs('/path/to/file.csv');
<?php
use yii2\extensions\csvexport\CsvExporter;
use yii2\extensions\csvexport\SerialColumn;
use yii\data\ArrayDataProvider;
$exporter = new CsvExporter(
[
'dataProvider' => new ArrayDataProvider([
'allModels' => [
['name' => 'a', 'price' => 5],
],
]),
'showFooter' => true,
'columns' => [
['class' => SerialColumn::class],
'name',
[
'attribute' => 'price',
'header' => 'Price (USD)',
'footer' => 'Total',
'value' => static fn (array $model): string => number_format($model['price'], 2),
],
],
],
);
$exporter->export()->saveAs('/path/to/file.csv');

The file contains three records:

"#","Name","Price (USD)"
"1","a","5.00"
"","","Total"

send() returns the Yii web response, sets the MIME type from the result and removes the temporary files after the response is sent. It is not available in console applications.

<?php
use yii2\extensions\csvexport\CsvExporter;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\Response;
class ItemController extends Controller
{
public function actionExport(): Response
{
$exporter = new CsvExporter(
[
'dataProvider' => new ActiveDataProvider([
'query' => Item::find()->orderBy('id'),
]),
],
);
return $exporter->export()->send('items.csv');
}
}

There is no need to check whether the result is archived. The extension of the result is appended when the name does not end with it, so an archived export is offered as items.csv.zip.

Spreadsheet programs limit the rows of a file: 65536 in ‘Open Office’ and ‘MS Excel 97-2003’, 1048576 in ‘MS Excel 2007’. maxEntriesPerFile restricts the rows of each file, and several files are delivered as one archive.

<?php
use yii2\extensions\csvexport\CsvExporter;
$exporter = new CsvExporter(
[
'query' => Item::find()->orderBy('id'),
'maxEntriesPerFile' => 60000, // limit max rows per single file
'resultConfig' => ['forceArchive' => true], // archive even when the rows fit in one file
],
);
$exporter->export()->saveAs('/path/to/archive-file.zip'); // output ZIP archive!

To process the files yourself, iterate over ExportResult::$csvFiles while the result object is alive:

<?php
use yii2\extensions\csvexport\CsvExporter;
$exporter = new CsvExporter(
[
'query' => Item::find()->orderBy('id'),
'maxEntriesPerFile' => 60000,
],
);
$result = $exporter->export();
foreach ($result->csvFiles as $csvFile) {
copy($csvFile->name, '/path/to/dir/' . basename($csvFile->name));
}

Always archive, or use another archive format

Section titled “Always archive, or use another archive format”

forceArchive archives a single file too.

<?php
use yii2\extensions\csvexport\CsvExporter;
$exporter = new CsvExporter(
[
'query' => Item::find()->orderBy('id'),
'resultConfig' => [
'forceArchive' => true, // always archive the results
],
],
);
$exporter->export()->saveAs('/path/to/archive-file.zip');

A custom archiver receives the CSV paths and the private directory, and returns the archive it created there:

<?php
use yii2\extensions\csvexport\CsvExporter;
$exporter = new CsvExporter(
[
'query' => Item::find()->orderBy('id'),
'resultConfig' => [
'forceArchive' => true,
'archiver' => static function (array $files, string $dirName): string {
$archive = $dirName . DIRECTORY_SEPARATOR . 'items.tar';
$tar = new PharData($archive);
foreach ($files as $file) {
$tar->addFile($file, basename($file));
}
return $archive;
},
],
],
);
$exporter->export()->saveAs('/path/to/items.tar');
<?php
use yii2\extensions\csvexport\CsvExporter;
$exporter = new CsvExporter(
[
'query' => Item::find()->orderBy('id'),
'csvFileConfig' => [
'cellDelimiter' => "\t",
'rowDelimiter' => "\n",
'enclosure' => '',
],
],
);
$exporter->export()->saveAs('/path/to/file.txt');

Without an enclosure the export fails when a value contains a tab or a line break.

<?php
use yii2\extensions\csvexport\CsvExporter;
$exporter = new CsvExporter(
[
'query' => Item::find()->orderBy('id'),
'csvFileConfig' => [
'writeBom' => true,
'spreadsheetSafe' => true,
],
],
);
$exporter->export()->saveAs('/path/to/file.csv');

saveAs() stages the completed file beside the destination and then publishes it. It returns false when delivery fails and leaves the complete source in place, so the same result can be saved again. Pass false as the second argument to keep the temporary files after a successful save.

A destination directory that cannot be created, resolved or used for staging throws yii\base\Exception, and a destination inside the private workspace throws yii\base\InvalidConfigException. Nothing is published in either case and the source stays in place. The example below handles only the false result.

$result = $exporter->export();
if (!$result->saveAs('/path/to/file.csv')) {
$result->saveAs('/another/path/file.csv');
}
use yii2\extensions\csvexport\ExportResult;
$removed = ExportResult::purgeExpired('@runtime/csv-export', 86400);

Back to documentation