How to create a CSV file with PHP

Pretty straight forward function to create a CSV file (comma separated) using PHP.

Calling the function through an URL will automatically download the file.

function create_csv(){ /* Define the first row, name your fields */ $csv_output = "Field 1;Field 2;Field 3;Field 4"; $csv_output .= "\n"; /* Here you could get data from the DB*/ $csv_output .= mb_convert_encoding("Content Field 1;Content Field 2;Content Field 3;Content Field 4 \n", "ISO-8859-1", "UTF-8"); header("Content-type: application/"); /* Set your own File Name */ header("Content-disposition: attachment; filename= my_filename.csv"); print $csv_output; }
Code language: PHP (php)

About Ricard Torres

Senior Front-end Software Engineer at Netcentric, from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.

@ricard_dev @ricard_dev

📝 Blog 🎙 Podcast

Leave a Reply

Add <code> Some Code </code> if you need to.