Efficient CSV Export in PHP for Large Datasets
This article explains how to efficiently export large datasets to CSV files using PHP, describing the CSV format, why a simple streaming approach outperforms PHPExcel, performance expectations for 200,000 rows, and provides a complete PHP function that handles encoding, buffering, and memory‑friendly output.
CSV (Comma Separated Values) is a plain‑text format commonly used for data exchange.
If you only need to export data from Excel without advanced features, using a simple PHP CSV export is more efficient than PHPExcel.
Exporting about 200,000 rows typically takes 2–3 seconds.
The following PHP function demonstrates an efficient way to stream a CSV file directly to the browser, convert UTF‑8 strings to GBK to avoid garbled characters, and flush the output buffer every 100 000 rows to keep memory usage low.
/**
* Export excel(csv)
* @data Export data
* @headlist First row, column names
* @fileName Output Excel file name
*/
function csv_export($data = array(), $headlist = array(), $fileName) {
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');
header('Cache-Control: max-age=0');
// Open PHP file handle, php://output means output directly to browser
$fp = fopen('php://output', 'a');
// Output Excel column names
foreach ($headlist as $key => $value) {
// CSV's Excel supports GBK encoding, must convert, otherwise garbled
$headlist[$key] = iconv('utf-8', 'gbk', $value);
}
// Write column names to file handle
fputcsv($fp, $headlist);
// Counter
$num = 0;
// Flush output buffer every $limit rows, not too large nor too small
$limit = 100000;
// Process rows one by one to avoid memory waste
$count = count($data);
for ($i = 0; $i < $count; $i++) {
$num++;
// Flush buffer to prevent issues with too much data
if ($limit == $num) {
ob_flush();
flush();
$num = 0;
}
$row = $data[$i];
foreach ($row as $key => $value) {
$row[$key] = iconv('utf-8', 'gbk', $value);
}
fputcsv($fp, $row);
}
}Call csv_export($data, $headlist, $fileName) with your dataset, column headers, and desired file name to generate the download.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.