Create and download CSV files using PHP

Today, We want to share with you download csv file in php.In this post we will show you automatically download csv file in php, hear for php download csv file from url we will give you demo and example for implement.In this post, we will learn about Download Csv File In Php Example with an example.

create csv file using php and save it into directory

If you required 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, therefor you will have to loop over as well as collect the some lines.

And you required to use some special headers , those headers Disable caching HTTP, Proxies, say to the browser that the content you are going to send must be downloaded instead, as displayed on the browser as a regular HTML.

Creating downloadable CSV files using PHP

following is the simple function which will generate as well as results the CSV file on the fly

function directFourceDownloadCSVFile($data,$file_name = 'file.csv') {
       # results headers therefor that the file is easy to 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
        $results = fopen("php://output", "w");
        
         # Then loop through the rows
        foreach ($data as $row) {
            # Add the more rows to the body
            fputcsv($results, $row); // here you can update delimiter/enclosure
        }
        # Close the stream off
        fclose($results);
    }

How to Use

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

directFourceDownloadCSVFile(array(
        array("Lenova", "DELL", "OPPO"),
        array("Lenova 1", "DELL 1", "OPPO 1"),
        array("Lenova 2", "DELL 2", "OPPO 2"),
        array("Lenova 3", "DELL 3", "OPPO 3"),
    ),'pakainfo_download.csv');

I hope you get an idea about php download csv file from server.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment