Export data to CSV in PHP

0
55
PHP

This tutorial explains how to export database data in CSV file in PHP.

Here is the example to export Mysql database table data in CSV file.

$sql="select id, name, email from Users"; // we are selecting data from users table
 $conn = mysql_connect($servername, $username, $password, $dbname);
// setup your database connection in above line


header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=paytm_payments.csv');

// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');

// output the column headings
fputcsv($output, array('ID', 'Name', 'Email' ));
$rows = mysql_query($sql);
while ($row = mysql_fetch_assoc($rows)) 
{
fputcsv($output, $row);
}

LEAVE A REPLY

Please enter your comment!
Please enter your name here