During WordPress development, we often run into cases where data needs to be exported to XLS or CSV. One powerful solution is to use the PHPExcel class, but more power often means more complexity. In this article, we will introduce a simpler way to export data to CSV.

A pure PHP helper function for exporting an array as CSV
The function has three parameters: the array to convert, the output file name, and the delimiter used between values, which is usually a comma.
function wizhi_convert_to_csv($input_array, $output_file_name, $delimiter) {
/** Open memory as a file, so there is no need to create a temporary file. */
$temp_memory = fopen('php://memory', 'w');
/** Loop through the array. */
foreach ($input_array as $line) {
/** Default PHP CSV handler. **/
fputcsv($temp_memory, $line, $delimiter);
}
/** Rewind the "file" containing the CSV lines. **/
fseek($temp_memory, 0);
/** Change the headers so the output is downloaded as a CSV file. **/
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="' . $output_file_name . '";');
/** Send the file to the browser for download. */
fpassthru($temp_memory);
}
How to use the pure PHP CSV export function
$array_to_csv = Array(
Array(12566,
'Enmanuel',
'Corvo'
),
Array(56544,
'John',
'Doe'
),
Array(78550,
'Mark',
'Smith'
)
);
wizhi_convert_to_csv($array_to_csv, 'report.csv', ',');
In WordPress, you only need to convert the data you want to export into an array and pass it into the function above as an argument. It is very convenient.
