Ec (2); how to create a CSV file method 1-use the HTTP header as in Word and Excel, you need to add the header information to the PHP script example. The following code snippet creates a specified table including its column name CSV file. Then the user is prompted to download the file. & Lt ;? Php $ tabletable_name; $ outstrNULL; header (& quot; Content-Type: applicationcsv script ec (2); script
How to Create a CSV file
Method 1-use the HTTP Header
For Word and Excel, you need to add the header information to the PHP script example.
The following code snippet creates a specified table including its column name CSV file. Then the user is prompted to download the file.
$ Table = 'table _ name ';
$ Outstr = NULL;
Header ("Content-Type: application/csv ");
Header ("Content-Disposition: attachment?filename=cars-models.csv ");
$ Conn = mysql tutorial _ connect ("localhost", "mysql_user", "mysql_password ");
Mysql_select_db ("db", $ conn );
// Query database to get column names
$ Result = mysql_query ("show columns from $ table", $ conn );
// Write column names
While ($ row = mysql_fetch_array ($ result )){
$ Outstr. = $ row ['field']. ',';
}
$ Outstr = substr ($ outstr, 0,-1 )."";
// Query database to get data
$ Result = mysql_query ("select * from $ table", $ conn );
// Write data rows
While ($ row = mysql_fetch_assoc ($ result )){
$ Outstr. = join (',', $ row )."";
}
Echo $ outstr;
Mysql_close ($ conn );
?>
Method 2-Use fputcsv ()
Use the fputcsv () function format as a CSV row and write it into an open file. For more information, see
For more information, see http://php.net/manual/en/function.fputcsv.php.
The following code snippet creates a column name for the specified table, including a CSV file, and sends it to the browser.
$ Table = 'table _ name ';
$ Filename = tempnam (sys_get_temp_dir (), "csv ");
$ Conn = mysql_connect ("localhost", "mysql_user", "mysql_password ");
Mysql_select_db ("db", $ conn );
$ File = fopen ($ filename, "w ");
// Write column names
$ Result = mysql_query ("show columns from $ table", $ conn );
For ($ I = 0; $ I <mysql_num_rows ($ result); $ I ++ ){
$ ColArray [$ I] = mysql_fetch_assoc ($ result );
$ FieldArray [$ I] = $ colArray [$ I] ['field'];
}
Fputcsv ($ file, $ fieldArray );
// Write data rows
$ Result = mysql_query ("select * from $ table", $ conn );
For ($ I = 0; $ I <mysql_num_rows ($ result); $ I ++ ){
$ DataArray [$ I] = mysql_fetch_assoc ($ result );
}
Foreach ($ dataArray as $ line ){
Fputcsv ($ file, $ line );
}
Fclose ($ file );
Header ("Content-Type: application/csv ");
Header ("Content-Disposition: attachment?filename=cars-models.csv ");
// Send file to browser
Readfile ($ filename );
Unlink ($ filename );
?>