Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ajaxray/8a154c79fc3e41fa4959 to your computer and use it in GitHub Desktop.
Save ajaxray/8a154c79fc3e41fa4959 to your computer and use it in GitHub Desktop.

Revisions

  1. @vrushank-snippets vrushank-snippets created this gist Dec 13, 2012.
    28 changes: 28 additions & 0 deletions PHP : Array To CSV - Download CSV File
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    $fileName = 'Billing-Summary.csv';

    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header('Content-Description: File Transfer');
    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename={$fileName}");
    header("Expires: 0");
    header("Pragma: public");

    $fh = @fopen( 'php://output', 'w' );

    $headerDisplayed = false;

    foreach ( $results as $data ) {
    // Add a header row if it hasn't been added yet
    if ( !$headerDisplayed ) {
    // Use the keys from $data as the titles
    fputcsv($fh, array_keys($data));
    $headerDisplayed = true;
    }

    // Put the data into the stream
    fputcsv($fh, $data);
    }
    // Close the file
    fclose($fh);
    // Make sure nothing else is sent, our file is done
    exit;