我想将 symfony 实体导出到 CSV。我现在有这个代码:
$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] 进行调试:
Member {#1360 ▼ -association: Association {#1444 ▶} -locality: Locality {#1421 ▶} -salutation: Salutation {#1409 ▶} -country: Country {#1454 ▶} -id: 844 -name: "TestName" -firstname: "TestFirstname" -date: DateTime {#1362 ▶} -email: "[email protected]" -phone: "123456789" -address: "Road 4, CH" -description: null }
我认为问题是因为我的对象中有对象。导出内部有对象的实体的正确方法是什么?
谢谢
最佳答案
不,问题正是警告所说的:fputcsv()期望第二个参数是一个数组,并且您向它传递一个对象(在本例中,根据您的转储输出,是 Member
的一个实例)
要修复它,您至少需要将对象转换为数组
fputcsv($handle, (array) $row[0]);
或者实现类似 Member::toArray()
的东西并使用它
fputcsv($handle, $row[0]->toArray());
或者,实现一个库来帮助您执行此操作,例如 CSV from the PHP League .
关于php - 将 Symfony 实体导出为 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32571935/