csv download header problem

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
speedamp
Forum Commoner
Posts: 45
Joined: Tue Apr 29, 2003 3:59 pm

csv download header problem

Post 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
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post 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");
Post Reply