Make tabular Data downloadable as a CSV file

I have a website which offers data in standard HTML table form and is displayed across 7 columns. At the backend, data is stored in MySQL and displayed through PHP on the webpage.

Site visitors have been demanding that data be made available for download in a CSV file, and I am OK to offer that feature.

What is the best way to offer a limited number of columns (say 3 out of 7 columns) with a one-click download into CSV file?

Note: this question is NOT about site visitors scrapping data using python or other scripts, but it is about a webmaster willingly offering the option to download data in a CSV file.

Searched for and checked this thread XML or CSV for “Tabular Data”, but it does not have a precise answer, hence the question.


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Create a new PHP file (page) that instead of rendering the content as HTML will render it as a CSV. Then manipulate response headers to make clear to the browser that it is a file meant to be downloaded. This is how your .php file should look like:


    header('Content-Description: File Transfer');
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="file.csv"');

    // ... QUERY FOR DATA

    $outstream = fopen("php://output", 'w');
    function __outputCSV(&$vals, $key, $filehandler) {
      fputcsv($filehandler, $vals, ',', '"');
    // CSV header
    __outputCSV(['header1', 'header2', ...]);
    // CSV body
    array_walk($data, '__outputCSV', $outstream);


All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x