dongshi2458 2014-01-15 00:51
浏览 64

如何在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();
  • 写回答

2条回答 默认 最新

  • doucou19961205 2014-01-15 09:00
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)