PHP CSV File Export Using fputcsv()

by Vincy. Last modified on October 29th, 2022.

In this tutorial, we are going to export MySQL records to a CSV File using PHP function fputcsv(). In the previous article, we have formatted the array of database results as CSV string. But by using fputcsv() function we need not format data to export it to a .csv file.

View Demo

PHP fputcsv()

In this example, the fputcsv() function accepts an array of database results and a file resource pointer. This array of results is converted into the CSV format and written to the target .csv file with the reference of the given file pointer.

The syntax of this function is,

fputcsv($file_pointer, $input_array, $delimiter = ',', $enclosure = '"');

In this code, we are creating the file pointer by opening PHP output stream. And then, we set this pointer and database field array to the fputcsv() function. This function will be called after setting the header with content-type, disposition, and CSV file name. The PHP code is,

<?php
$conn = mysqli_connect("localhost", "root", "", "php_csv_export");
$filename = "toy_csv.csv";
$fp = fopen('php://output', 'w');
$tableschema = 'php_csv_export';
$tablename = 'toy';
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA= ? AND TABLE_NAME =?";
$statement = $conn->prepare($sql);
$statement->bind_param('ss', $tableschema, $tablename);
$statement->execute();
$result = $statement->get_result();
while ($row = $result->fetch_array()) {
    $header[] = $row[0];
}
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename=' . $filename);
fputcsv($fp, $header);
$sql = "SELECT * FROM toy";
$statement = $conn->prepare($sql);
$statement->execute();
$result = $statement->get_result();
while ($row = $result->fetch_assoc()) {
    fputcsv($fp, $row);
}
exit();
?>

View DemoDownload

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

↑ Back to Top

Share this page