PHP Export as CSV
Posted on February 22, 2008
A client recently requested an option to extract search results from their PHP application as CSV. It had me confused for a while, I was writing wrappers, writing out files, changing directory permissions, until I had a lightbulb moment.
There is no reason why you can't have the browser do all the work for you.
Here's how;
On the existing search page, I added a check box to return the results as CSV.
In the POST area of your code ,do your SQL query as normal
$SQL = 'SELECT * FROM company_stuff WHERE meaningful_content = 'NONE';';
$rs = $conn->Execute($SQL);
if (!$rs_max) { throw_sql_error(); }
Then slam the following code above where you normally would return the results on screen.
if (isset($_POST['return_as_csv'])) {
$filename = strtolower('your_filename.csv');
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="'.$filename.'".');
// column headers
echo '"Col 1","Col 2","Col 3","Col 4","Col 5","Col 5,"Col 6","Col 7"'."n";
// loop over recordset
foreach ($rs_max as $row) {
echo '"Col 1","Col 2","Col 3","Col 4","Col 5","Col 5,"Col 6","Col 7"'."n";
}
}
else {
// existing code here to display results on screen.
}
It simply tells the browser to return the results as a CSV file and the user is prompted to download the file.
Easy!
Related posts
- Shopp Alternative Google Base Feed
So you're running a Shopp, you're going to need a Google Base Feed to stand... - iCalendar Generation
One of my clients requested that the CRM applicationI wrote should interact with Outlook Calender.... - Detecting MIME types in PHP
Detecting MIME types in PHP used to be hellish. Use the mime_content_type function I hear... - Using WP-Ecommerce Product Downloads without checking out
I've used WP-Ecommerce for a few clients who required an online catalogue, rather than an... - Nice print_r() for the web
Here's a nicer version of the print_r() function that displays much better on web pages....


