In this post, we are going to discuss how to export MySQL table into CSV using fputcsv() function in PHP.
In our previous tutorial, you have seen how to export MySQL table data to CSV in PHP without using inbuilt function.
Now in this article we will see how to implement same functionality with fputcsv() function.
First of all we have to understand what fputcsv() function work and how to use it. We are going discuss about fputcsv() function in detail.
PHP fputcsv function
fputcsv(file,fields,seperator,enclosure)
In this snippet, we are creating a file by open PHP output with use of fopen() function as you can see below. After that we set file opened with fopen function and mysql table record array (like $rows) to fputcsv function. Now fputcsv function is used after setting header with content type and content disposition with filename for CSV.
See the snippet to given below to get better.
[sociallocker]Download[/sociallocker]
Source Code
<?php mysql_connect("localhost","root",""); mysql_select_db("DB"); $f=fopen("php://output","wt"); //field name from Table $result = mysql_query("select * from `TABLE_NAME`"); $col_count = mysql_num_fields($result); for($i=0;$i<$col_count;$i++) { $column[]=mysql_field_name($result,$i); } fputcsv($f,$column); //get records of field while($rows = mysql_fetch_row($result)) { fputcsv($f,$rows); } // download CSV $file= "prod.csv"; header('Content-Type: text/csv'); header('Content-Disposition: attachment; filename='.$file); exit; ?>