如何在Symfony中将实体导出为CSV? [英] How to export an entity as a CSV in Symfony?

查看:77
本文介绍了如何在Symfony中将实体导出为CSV?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码输出CSV,但是运行它时出现空白屏幕.基本上,我对DoctrineORMQuerySourceIterator感到困惑,因为我不了解如何正确使用它.我假设我必须列出属性名称????

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 ????

我正在使用Sonata Exporter:

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();

推荐答案

DoctrineORMQuerySourceIterator的secound参数是属性名称的数组,如下所示:

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).

如果要从数据库导出原始数据,我建议使用 DoctrineDBALConnectionSourceIterator 代替,因为它们更快.前者需要一个PDOStatement,而另一个则需要一个连接,一个查询和一个参数表(您可以在链接的源代码中看到它)作为构造函数参数.

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.

这篇关于如何在Symfony中将实体导出为CSV?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆