Page 1 of 1

csv download header problem

Posted: Thu Apr 08, 2004 3:30 pm
by speedamp
hello everybody....i am really close to finishing this program which will output csv text data from mysql database so the client can download a copy to their desktop.

however i need to format this to include a FIRST LINE that wil print the field names.

anybody have any idea how i would do this?

----------------------------------------------

<?php

include("config.php");

$connect = mysql_connect("$user_hostname", "$user_username", "$user_password");
mysql_select_db("$user_database", $connect);

$F = fopen('results_full.csv' , 'w'); // open for write
$delim = ",";
$res = mysql_query("SELECT * FROM $table");
while ($row = mysql_fetch_row($res)) {
fwrite($F, join($delim, $row) . "\n");
}
fclose($F);

header("Content-Type: text/plain");
header("Pragma: cache");
header('Content-Disposition: attachment; filename=results_full.csv');
header("Expires: 0");
readfile('results_full.csv');
?>

?>
------------------------------------------------------------

thanks,
-mike

Posted: Thu Apr 08, 2004 3:51 pm
by markl999
You could put this right before the while() loop.

Code: Select all

$numfields = mysql_num_fields($res);
for($x=0;$x<$numfields;$x++){
  $titles[] = mysql_field_name($res, $x);
}
fwrite($F, join($delim, $titles) . "\n");