我想将CSV导出为symfony实体。我暂时有这个代码:
$em = $this->getDoctrine()->getEntityManager();
$iterableResult = $em->getRepository('AppBundle:Member')
->createQueryBuilder('m')
->where('m.association = :id')
->setParameter('id', $id)
->getQuery()
->iterate();
$handle = fopen('php://memory', 'r+');
$header = array();
while (false !== ($row = $iterableResult->next())) {
dump($row[0]);
fputcsv($handle, $row[0]);
$em->detach($row[0]);
}
rewind($handle);
$content = stream_get_contents($handle);
fclose($handle);
return new Response($content, 200, array(
'Content-Type' => 'application/force-download',
'Content-Disposition' => 'attachment; filename="export.csv"'
));
但我有这个错误:
Warning: fputcsv() expects parameter 2 to be array, object given
如您所见,我转储$ row [0]进行调试:
会员{#1360▼ -association:Association {#1444▶} -locality:Locality {#1421▶} -sututation:Salutation {#1409▶} - 国家:国家{#1454▶} -id:844 -name:“TestName” -firstname:“TestFirstname” -date:DateTime {#1362▶} -email:“email@domain.com” 电话:“123456789” - 地址:“4号路,CH” -description:null }
我认为问题是因为我的对象中有对象。导出具有对象的实体的正确方法是什么?
由于
答案 0 :(得分:3)
不,问题正是警告所说的:fputcsv()期望第二个参数是一个数组并且你将它传递给一个对象(在这种情况下,基于你的转储输出,一个实例) Member
)
要解决此问题,您至少需要将对象转换为数组
fputcsv($handle, (array) $row[0]);
或者实现Member::toArray()
之类的内容并使用
fputcsv($handle, $row[0]->toArray());
或者,实施一个帮助您执行此操作的库,如CSV from the PHP League。
答案 1 :(得分:0)
最后,我使用了sonata-exporter bundle
现在正在工作