Search This Blog

Friday, August 12, 2011

best php export to csv without space or comma

$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// DB Connection here
$db = mysql_select_db("test",$con);

$result = mysql_query("SELECT * FROM test1");
csvToExcelDownloadFromResult($result);
function csvToExcelDownloadFromResult($result, $showColumnHeaders = true, $asFilename = 'data.csv') {
setExcelContentType();
setDownloadAsHeader($asFilename);
return csvFileFromResult('php://output', $result, $showColumnHeaders);
}

function csvFileFromResult($filename, $result, $showColumnHeaders = true) {
$fp = fopen($filename, 'w');
$rc = csvFromResult($fp, $result, $showColumnHeaders);
fclose($fp);
return $rc;
}
function setExcelContentType() {
if(headers_sent())
return false;

header('Content-type: application/vnd.ms-excel');
return true;
}

function setDownloadAsHeader($filename) {
if(headers_sent())
return false;

header('Content-disposition: attachment; filename=' . $filename);
return true;
}
function csvFromResult($stream, $result, $showColumnHeaders = true) {
if($showColumnHeaders) {
$columnHeaders = array();
$nfields = mysql_num_fields($result);
for($i = 0; $i < $nfields; $i++) { $field = mysql_fetch_field($result, $i); $columnHeaders[] = $field->name;
}
fputcsv($stream, $columnHeaders);
}

$nrows = 0;
while($row = mysql_fetch_row($result)) {
fputcsv($stream, $row);
$nrows++;
}

return $nrows;
}

No comments:

Post a Comment