Skip to content

Create and download CSV files using PHP

If you need to download a CSV file on the fly without writing to external file, than you need to open php://output stream and use fputcsv() on it.

Built in fputcsv() will generate CSV lines from given array, so you will have to loop over and collect the lines.

And you need to use some special headers , those headers tell to the browser that the content you are going to send must be downloaded instead, as displayed on the browser as a regular HTML.

Below is the simple function which will generate and output the CSV file on the fly


    function outputCSV($data,$file_name = 'file.csv') {
       # output headers so that the file is downloaded rather than displayed
        header("Content-Type: text/csv");
        header("Content-Disposition: attachment; filename=$file_name");
        # Disable caching - HTTP 1.1
        header("Cache-Control: no-cache, no-store, must-revalidate");
        # Disable caching - HTTP 1.0
        header("Pragma: no-cache");
        # Disable caching - Proxies
        header("Expires: 0");
    
        # Start the ouput
        $output = fopen("php://output", "w");
        
         # Then loop through the rows
        foreach ($data as $row) {
            # Add the rows to the body
            fputcsv($output, $row); // here you can change delimiter/enclosure
        }
        # Close the stream off
        fclose($output);
    }

How to Use

Just call the function with array as the first parameter and second parameters is file name and it is optional.

    outputCSV(array(
        array("Volvo", "BMW", "Toyota"),
        array("Volvo 1", "BMW 1", "Toyota 1"),
        array("Volvo 2", "BMW 2", "Toyota 2"),
        array("Volvo 3", "BMW 3", "Toyota 3"),
    ),'download.csv');

Function refernce

  • fputcsv() — Format line as CSV and write to file pointer
  • fopen() — Opens file or URL
  • foreach() — Format line as CSV and write to file pointer
  • fclose() — Closes an open file pointer
0 0 votes
Article Rating
Subscribe
Notify of
guest

5 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments