php – 如何在Symfony中将实体导出为CSV?
作者:互联网
我使用以下代码输出CSV,但是当我运行它时,我得到一个空白屏幕.基本上我的困惑是DoctrineORMQuerySourceIterator,因为我不知道如何正确使用它.我假设我必须列出属性名称????
我正在使用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();
解决方法:
DoctrineORMQuerySourceIterator的secound参数是一个属性名称数组,如下所示:
['Column name in the output' => 'fieldName', 'Something' => 'address.street']
正如您在source code中看到的,它实际上使用Property Accessor组件来访问数据(您可以在那里找到更多示例).
如果你想从db导出原始数据,我建议使用PDOStatementSourceIterator
或DoctrineDBALConnectionSourceIterator
,因为它们更快.前者需要PDOStatement,另一个需要连接,查询和参数数组(您可以在链接的源代码中看到它)作为构造函数参数.
标签:export-to-csv,php,symfony 来源: https://codeday.me/bug/20191006/1858643.html