如何在Symfony中将实体导出为CSV?

I am using the following code to output a CSV but I am getting a blank screen when I run it. basically my confusion is with the DoctrineORMQuerySourceIterator as I am not understanding how to use that properly. I am assuming I have to list out the property names ????

I am using the Sonata Exporter:

https://github.com/sonata-project/exporter

<?php

$repository = $this->getDoctrine()->getRepository('MainReferralCaptureBundle:Referral');
$referrals = $repository->createQueryBuilder('r')->select('r.pLastName, r.pFirstName')->getQuery();

// $referrals2 = $referrals->getResult();
// var_dump($referrals2);

$data = array(
    0 => array('name' => 'Jack'),
    1 => array('name' => 'Jill')
);

// Pick a format to export to
$format = 'csv';

// Filename
$filename = 'referral.csv';

// Set Content-Type
$content_type = 'text/csv';

// Location to Export this to
$export_to = 'php://output';

// Data to export
$exporter_source = new \Exporter\Source\DoctrineORMQuerySourceIterator($referrals, array('pLastName, pFirstName'));

// Get an Instance of the Writer
$exporter_writer = '\Exporter\Writer\\' . ucfirst($format) . 'Writer';

$exporter_writer = new $exporter_writer($export_to);

// Set the right headers
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Description: File Transfer');
header('Content-type: ' . $content_type);
header('Content-Disposition: attachment; filename=' . $filename . ';');
header('Expires: 0');
header('Pragma: public');

// Export to the format
\Exporter\Handler::create($exporter_source, $exporter_writer)->export();

The secound parameter of the DoctrineORMQuerySourceIterator is an array of property names like this:

['Column name in the output' => 'fieldName', 'Something' => 'address.street']

As you can see in the source code it actually uses the Property Accessor component to access the data (you can find more examples there).

If you want to export raw data form the db, I rocommend to use the PDOStatementSourceIterator or the DoctrineDBALConnectionSourceIterator instead as those are faster. The former requires a PDOStatement and the other requires a connection, a query and an array of prameters (you can see it in the linked source code) as constructor parameters.

A working example using the CsvWriter :

$format = 'csv';
$exportTo = 'php://output';
$exporterWriter = '\Exporter\Writer\\' . ucfirst($format) . 'Writer';

$data = $repository->createQueryBuilder('r')->getQuery();
$fields = array('Last Name' => 'pLastName', 'First Name' => 'pFirstName');
$source = new DoctrineORMQuerySourceIterator($data, $fields);
$writer = new $exporterWriter($exportTo);

Handler::create($source, $writer)->export();

Sorry for the delay before answer your issue.