Created
April 17, 2012 14:28
-
-
Save maciakl/2406298 to your computer and use it in GitHub Desktop.
PHP: Export Query Results to a CSV File
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// (c) 2007 Lukasz Grzegorz Maciak | |
// Code Snippet ID: 5e8cf864-db67-4a30-9857-2ce8f3fcb1d5 | |
// takes a database resource returned by a query | |
function csv_from_mysql_resource($resource) | |
{ | |
$output = ""; | |
$headers_printed = false; | |
while($row = mysql_fetch_array($resource, MYSQL_ASSOC)) | |
{ | |
// print out column names as the first row | |
if(!$headers_printed) | |
{ | |
$output .= join(',', array_keys($row)) ."\n"; | |
$headers_printed = true; | |
} | |
// remove newlines from all the fields and | |
// surround them with quote marks | |
foreach ($row as &$value) | |
{ | |
$value = str_replace("\r\n", "", $value); | |
$value = "\"" . $value . "\""; | |
} | |
$output .= join(',', $row)."\n"; | |
} | |
// set the headers | |
$size_in_bytes = strlen($output); | |
header("Content-type: application/vnd.ms-excel"); | |
header("Content-disposition: attachment; filename=export_data.csv; size=$size_in_bytes"); | |
// send output | |
print $output; | |
exit; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment