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
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.
//field name from Table
$result = mysql_query("select * from `TABLE_NAME`");
$col_count = mysql_num_fields($result);
//get records of field
while($rows = mysql_fetch_row($result))
// download CSV
header('Content-Disposition: attachment; filename='.$file);