How to export an entity as a CSV in Symfony?

放肆的年华 提交于 2019-11-30 16:13:45

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!