2014-01-15 37 views
1

這裏是我的代碼,我使用https://github.com/sonata-project/exporterCSV導出顯示HTML和數據。爲什麼?

$data = array(
        0 => array(
         'name' => 'Jack' 
        ), 
        1 => array(
         'name' => 'Jill' 
        ) 
       ); 

    $format = 'csv'; 

        // Filename 
        $filename = 'referral.csv'; 

        // Set Content-Type 
        $content_type = 'text/csv'; 

        // Location to Export this to 
        $export_to = 'php://output'; 

        // Data to export 
        $exporter_source = new \Exporter\Source\ArraySourceIterator($data); 

        // Get an Instance of the Writer 
        $exporter_writer = '\Exporter\Writer\\' . ucfirst($format) . 'Writer'; 

        $exporter_writer = new $exporter_writer($export_to); 

        // Set the right headers 
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
        header('Content-Description: File Transfer'); 
        header('Content-type: ' . $content_type); 
        header('Content-Disposition: attachment; filename=' . $filename . ';'); 
        header('Expires: 0'); 
        header('Pragma: public'); 

        // Export to the format 
        \Exporter\Handler::create($exporter_source, $exporter_writer)->export(); 

當我執行下面的代碼,它下載具有陣列數據的CSV文件,而且還具有HTML的頁面。我怎樣才能讓導出只包含數據數組的元素?

+0

等等才意識到,我必須做的是我最後的呼叫和固定後調用exit它。 – kratos

+0

呼叫出口實際​​上是你可以做的最糟糕的事情... – 1ed

+0

謝謝。我將在下面研究您的示例並相應地修復我的代碼。再次感謝 – kratos

回答

2

此代碼是從SonataCoreBundle,所以它是很好的內存消耗它流的respose到客戶端:

use Exporter\Source\SourceIteratorInterface; 
use Symfony\Component\HttpFoundation\StreamedResponse; 

use Exporter\Writer\XlsWriter; 
use Exporter\Writer\XmlWriter; 
use Exporter\Writer\JsonWriter; 
use Exporter\Writer\CsvWriter; 

// ... 

public function exportAction() 
{ 
    $data = array(array('name' => 'Jack'), array('name' => 'Jill')); 
    $source = new \Exporter\Source\ArraySourceIterator($data); 
    $filename = 'file.csv' 
    $format = 'csv'; 

    switch ($format) { 
     case 'xls': 
      $writer  = new XlsWriter('php://output'); 
      $contentType = 'application/vnd.ms-excel'; 
      break; 
     case 'xml': 
      $writer  = new XmlWriter('php://output'); 
      $contentType = 'text/xml'; 
      break; 
     case 'json': 
      $writer  = new JsonWriter('php://output'); 
      $contentType = 'application/json'; 
      break; 
     case 'csv': 
      $writer  = new CsvWriter('php://output', ',', '"', "", true, true); 
      $contentType = 'text/csv'; 
      break; 
     default: 
      throw new \RuntimeException('Invalid format'); 
    } 

    $callback = function() use ($source, $writer) { 
     $handler = \Exporter\Handler::create($source, $writer); 
     $handler->export(); 
    }; 

    return new StreamedResponse($callback, 200, array(
     'Content-Type'  => $contentType, 
     'Content-Disposition' => sprintf('attachment; filename=%s', $filename) 
    )); 
}