Page 1 of 1

Question creating a csv

Posted: Wed Jan 21, 2004 12:24 am
by rogz
Hello there

I'm currently looking to see what kind of difficulty it would be to generate a file with php and then push the contents of the file to excel where the user will have to save the file. I do not need to save the file anywere on the web server, just simply generate the contents of the file and have it displayed in excel.

thanks

Posted: Wed Jan 21, 2004 2:39 am
by Dr Evil
Here is a code I wrote a long ime ago (in French)

Code: Select all

<?php
header("Content-type: application/octet-stream"); 
header("Content-Disposition: attachment; filename=table.csv"); 
header("Content-Transfer-Encoding: binary"); 

include ("Connections/localhost.php"); //contains all connection params

$connection = mysql_connect ("$hostname_localhost", "$username_localhost", "$password_localhost");
	$query = "SELECT * FROM sirca_concours";
	$result= mysql_db_query ("$database_localhost", $query);
	$numOfRows = mysql_num_rows($result); 

for ($i = 0; $i < $numOfRows; $i++){
	$civilite 	= mysql_result ($result, $i, civilite);
	$prenom		= mysql_result ($result, $i, prenom);
	$nom		= mysql_result ($result, $i, nom);
	$adresse1 	= mysql_result ($result, $i, adresse1);
	$adresse2	= mysql_result ($result, $i, adresse2);
	$ville		= mysql_result ($result, $i, ville);
	$npa		= mysql_result ($result, $i, npa);
	$pays		= mysql_result ($result, $i, pays);
	$email		= mysql_result ($result, $i, email);

print ""$civilite","$prenom","$nom","$adresse1","$adresse2","$ville","$npa","$pays","$email"\n"; 
} 
?>
This code outputs certain lines from the DB. As you see it is like sending the info to a normal web page. You just add the new header before. CSV (comma separated value) is the standars simple text file for Excel. The fileds are formatted as follows:
"field1", "field2", "field3" \n
(\n is a new line)

Hope this helps
Dr Evil