From the course: PHP: Exporting Data to Files

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Outputting the result as a CSV file

Outputting the result as a CSV file - PHP Tutorial

From the course: PHP: Exporting Data to Files

Start my 1-month free trial

Outputting the result as a CSV file

Downloading data to a CSV file is a convenient way of exporting information in a portable format. CSV stands for comma, or character separated values, and it's widely used for transferring data to a spreadsheet or database. And PHP has a function that handles it for your automatically. In my editing program I've got open cars_csv.php. This is the same file that was created in chapter one. The only difference is that it's got a different label on the download button. The code on line two includes the database result. I'm using the MySQLI version. Change this to the PDO version if necessary. So we need to add another line in our PHP block at the top. After we've included the database result, what we need to do is to check whether the form has been submitted. So, we need a conditional statement. If is set, then we're looking in the post array for download. Inside that conditional statement, we need to create some headers to tell the browser to expect a file, so use the header function…

Contents