为什么csv导出不起作用?

时间:2017-10-08 00:00:06

标签: symfony export-to-csv

我尝试在我的symfony项目上进行csv导出,我觉得有些错误,因为该函数返回一个简单的响应并且不会下载csv。

这是功能:

public function exportCsv($customers)
{

    $fileName = "export_" . date("d_m_Y") . ".csv";
    $response = new StreamedResponse();

        $handle = fopen('php://output', 'w+');

        fputcsv($handle, array('Name',
            'Adress',
            'City',
            'Code'
        ), ';');


        foreach ($customers as $index => $custom)
        {

            fputcsv($handle,array(
                $custom->getName(),
                $custom->getAdress(),
                $custom->getCity(),
                $client->getCode(),
            ),';');
        }

        fclose($handle);

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

    return $response;

}

1 个答案:

答案 0 :(得分:0)

创建流式响应对象后,您需要添加回调函数,该函数将使用内容$response->setCallback()填充您的响应对象。

public function exportCsv($customers)
{

    $fileName = "export_" . date("d_m_Y") . ".csv";
    $response = new StreamedResponse();


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

      fputcsv($handle, array('Name', 'Adress', 'City', 'Code'),';');

      foreach ($customers as $index => $custom)
      {

          fputcsv($handle,array(
              $custom->getName(),
              $custom->getAdress(),
              $custom->getCity(),
              $client->getCode(),
          ),';');
      }

      fclose($handle);
    });

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

    return $response;

}