PHP Export as CSV

February 22nd, 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.

untitled.JPG

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!

Was this post useful to you? Let me know, buy me a beer!
Alternatively, if you're feeling impecunious, you may like to subscribe to my RSS feed, or see other articles in the PHP category.

Leave a Reply