I would like to teach about exporting data as CSV in PHP. First, CSV is a file format called Comma Seperated Values. It can be opened using MS Excel or other similar spreadsheet software. Consider a scenario where, you have a large website and it has about 10,000 registered users. You would like to get the list of users who registered in the month of August 2013 to send them a mail, for an offer.
First create a PHP file, for database connection.
// Create connection
$file = fopen("email_ids.csv","w");
if (mysqli_connect_errno()) // Check connection
echo "Failed to connect to MySQL: " . mysqli_connect_error();
// Perform queries
$query_res = mysqli_query($con,"SELECT `email` FROM `user_details` WHERE `date` BETWEEN '08-01-2013' AND '08-31-2013'");
Just you need to add two lines to your code. fopen(“email_ids.csv”,”w”); Which opens a file called “email_ids.csv” in write mode. And fputcsv($file,$row); which puts the array as each row into the csv file.
After successful execution of the php file, a new csv file will be created on the same location where php file is located.
Thanks for reading.
Latest posts by Nagarajan (see all)