Reputation: 883
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 scraping 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.
Upvotes: 1
Views: 83
Reputation: 4829
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:
<?php
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);
fclose($outstream);
?>
Upvotes: 2