我试图在我的Symfony项目中创建一个函数,该函数根据搜索词在数据库上运行查询,检索数据,然后生成CSV并下载它。我已经遵循了一些关于如何做到这一点的指南,虽然函数没有失败,但它似乎也不起作用。从Symfony2生成并下载CSV
下面是运行生成CSV功能:
public function exportCSVAction($filter)
{
$container = $this->container;
$response = new StreamedResponse(function() use($container,$filter) {
$em = $container->get('doctrine')->getManager();
$project_repo = $em->getRepository('AppBundle:Project');
$results = $project_repo->getSearchResults($filter,true);
$handle = fopen('php://output', 'w+');
while (false !== ($row = $results)) {
fputcsv($handle, $row[0]);
$em->detach($row[0]);
}
fclose($handle);
});
$response->headers->set('Content-Type', 'application/force-download');
$response->headers->set('Content-Disposition','attachment; filename="'.getcwd().'/csv/jobs-export.csv"');
return $response;
}
在我的仓库的getSearchResults
功能:
public function getSearchResults($filter,$array=false)
{
$qb = $this->createQueryBuilder('p')
->select('p')
->leftJoin('AppBundle:Oc73Customer', 'c', 'WITH', 'c.customerId = p.customerId')
->leftJoin('AppBundle:Oc73Product', 'pr', 'WITH', 'pr.productId = p.productId')
->where('c.firstname LIKE :filter')
->orWhere('c.lastname LIKE :filter')
->orWhere('pr.model LIKE :filter')
->orWhere('p.pONumber LIKE :filter')
->setParameter('filter', '%'.$filter.'%');
if($array == true) {
return $qb->getQuery()->getArrayResult();
} else {
return $qb->getQuery()->getResult();
}
}
正如你所看到的,如果$array
为真过去了,它返回一个CSV所需的数组结果。
我运行exportCSVAction
功能,如果一个特定的查询字符串传递:
if($request->get('export')) {
$this->exportCSVAction($request->get('s'));
}
它运行的网页是一个项目列表,并且如果“S”查询传递过滤。如果'导出'也通过,它将像上面那样运行exportCSVAction
。
该函数不会抛出错误,但它不会下载文件 - 我不知道如何调试它,因为代码被封装在$response
对象中,所以它在实际运行后才会返回。
如果任何人都可以解释这一点,我将不胜感激。
为什么不使用Xdebug的或VarDumper组件? –