csv导出不使用symfony 3

时间:2017-10-09 08:31:31

标签: symfony download export-to-csv

我尝试在我的symfony项目上进行csv导出,我觉得有些事情是错的,因为没有任何反应,我没有错误...... ??

public function exportCsv($customers)
{
$fileName = "export_" . date("d_m_Y") . ".csv";
$response = new StreamedResponse();


$response->setCallback(function() use ($customers){
    $handle = fopen('php://output', 'w+');

    // Nom des colonnes du CSV
    fputcsv($handle, array('Name',
        'Adress',
        'City',
        'Code'
    ), ';');

    //Champs
    foreach ($customers as $index => $customer)
    {
        //dump($client);die();
        fputcsv($handle,array(
            $customer->getName(),
            $customer->getAdress(),
            $customer->getCity(),
            $customer->getCode(),
        ),';');
    }
    fclose($handle);
});


$response->setStatusCode(200);
$response->headers->set('Content-Type', 'text/csv; charset=utf-8', 'application/force-download');
$response->headers->set('Content-Disposition','attachment; filename='.$fileName);


return $response;

}

我在我的控制器中调用此函数,如下所示:

if (isset($_POST['export']))
{
    $export = $exp->exportCsv($customers);

}

请你知道吗???

1 个答案:

答案 0 :(得分:0)

如果您想查看流式响应中发生的情况以及错误是什么,您只需在响应之外调用回调函数。

$callback = function() use ($customers){
    $handle = fopen('php://output', 'w+');

    // Nom des colonnes du CSV
    fputcsv($handle, array('Name',
        'Adress',
        'City',
        'Code'
    ), ';');

    //Champs
    foreach ($customers as $index => $customer)
    {
        //dump($client);die();
        fputcsv($handle,array(
            $customer->getName(),
            $customer->getAdress(),
            $customer->getCity(),
            $customer->getCode(),
        ),';');
    }
    fclose($handle);
};

$callback();exit;

刚刚删除最后一行并在StreamedResponse对象$response->setCallback($callback);内插入回调函数