Php function to convert an array to CSV file for download

Many times your PHP application may require downloading records from a database table. PHP MySQL select queries return result in associate array format (using mysqli_fetch_assoc or mysqli_result::fetch_assoc). Below function can be used to convert the result array into a CSV file. And then force download the generated CSV file.

Note that above function should be called before any headers are sent to the browser. In simple words call to the above function should occur before the <html>  tag. So code for an example php file using the above function is given below.

Leave a Reply

Your email address will not be published. Required fields are marked *