Skip to content

Instantly share code, notes, and snippets.

@mgrubinger
Created April 2, 2015 09:54
Show Gist options
  • Select an option

  • Save mgrubinger/8045537b8f53ea8391a4 to your computer and use it in GitHub Desktop.

Select an option

Save mgrubinger/8045537b8f53ea8391a4 to your computer and use it in GitHub Desktop.

Revisions

  1. mgrubinger created this gist Apr 2, 2015.
    33 changes: 33 additions & 0 deletions exportCSV
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@

    function export_csv() {
    $filename = "file_" . date('Y-m-d');

    // get csv data
    $data = $this->get_csv_data(); // expects: array with lines as array

    // define header
    $header = array('col1', 'col2', 'col3');

    // export
    toCSV($header, $data, $filename);
    }

    function toCSV($header, $data, $filename) {
    $sep = "\t";
    $eol = "\n";
    $csv = count($header) ? '"'. implode('"'.$sep.'"', $header).'"'.$eol : '';
    foreach($data as $line) {
    $csv .= '"'. implode('"'.$sep.'"', $line).'"'.$eol;
    }
    $encoded_csv = mb_convert_encoding($csv, 'UTF-16LE', 'UTF-8');
    header('Content-Description: File Transfer');
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="'.$filename.'.csv"');
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: '. strlen($encoded_csv));
    echo chr(255) . chr(254) . $encoded_csv;
    exit;
    }