How to create a CSV file from MySQL with PHP?

Create a CSV file from MySQL with PHP

simple copy and paste this code to create the csv file from mysql with php
and change the query according to your need.


<?php
mysql_connect('host','username','password');
mysql_select_db('database_name');
function remove_char($var)
{
$set = preg_replace('/[^a-zA-Z0-9-+@() \.\_\']/','padh',trim($var));
return $set;
}
function csv_create()
{
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=".date('Y-m-d-h:i:s').".csv");
header("Pragma: no-cache");
header("Expires: 0");
$res = mysql_query("SELECT fname,lname,fullname,email FROM cs_users order by id");
echo "First Name,Last Name,Full Name,Email\n";
// fetch a row and write the column names out to the file
while($val = mysql_fetch_array($res)) {
$fname = remove_char($val['fname']);
$lname = remove_char($val['lname']);
$fullname = remove_char($val['fullname']);
$email = remove_char($val['email']);
echo "$fname,$lname,$fullname,$email\n";
}
}
csv_create();
?>

Comments