2017-10-08 127 views
0

我嘗試在我的symfony項目上做一個CSV導出,我認爲這是錯誤的,因爲該函數返回一個簡單的響應,並且不下載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; 

} 

回答

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; 

} 
+0

好的!謝謝您的回答!!但它不工作..我添加這一行:$ response-> setCallback(function()use($ customers){});現在我沒有迴應...任何想法?也許我忘了頭? – Moh

+0

不知道?請幫幫我!!! – Moh

相關問題