Backend\Core\Engine\Csv::outputCSV PHP Method

outputCSV() public static method

Output a CSV-file as a download
public static outputCSV ( string $filename, array $array, array $columns = null, array $excludeColumns = null )
$filename string The name of the file.
$array array The array to convert.
$columns array The column names you want to use.
$excludeColumns array The columns you want to exclude.
    public static function outputCSV($filename, array $array, array $columns = null, array $excludeColumns = null)
    {
        // get settings
        $splitCharacter = Authentication::getUser()->getSetting('csv_split_character');
        $lineEnding = Authentication::getUser()->getSetting('csv_line_ending');
        // reformat
        if ($lineEnding == '\\n') {
            $lineEnding = "\n";
        }
        if ($lineEnding == '\\r\\n') {
            $lineEnding = "\r\n";
        }
        // convert into CSV
        $csv = \SpoonFileCSV::arrayToString($array, $columns, $excludeColumns, $splitCharacter, '"', $lineEnding);
        // set headers for download
        $charset = BackendModel::getContainer()->getParameter('kernel.charset');
        throw new RedirectException('Return the csv data', new Response($csv, Response::HTTP_OK, ['Content-type' => 'application/csv; charset=' . $charset, 'Content-Disposition' => 'attachment; filename="' . $filename . '"', 'Content-Length' => mb_strlen($csv), 'Pragma' => 'no-cache']));
    }

Usage Example

Example #1
0
 /**
  * Execute the action.
  */
 public function execute()
 {
     $this->id = $this->getParameter('id', 'int');
     // does the item exist
     if ($this->id !== null && BackendFormBuilderModel::exists($this->id)) {
         parent::execute();
         $this->setFilter();
         $this->setItems();
         BackendCSV::outputCSV(date('Ymd_His') . '.csv', $this->rows, $this->columnHeaders);
     } else {
         // no item found, redirect to index, because somebody is f*****g with our url
         $this->redirect(BackendModel::createURLForAction('Index') . '&error=non-existing');
     }
 }