From the course: PHP: Exporting Data to Files

Unlock the full course today

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

Outputting the database result to a text file

Outputting the database result to a text file - PHP Tutorial

From the course: PHP: Exporting Data to Files

Start my 1-month free trial

Outputting the database result to a text file

Generating a plain text file from a database result requires only a dozen or so lines of code. You don't even need to create a copy of the file for the user to download. The PHP script streams it directly to the browser with the appropriate HTTP headers. In my editing program, I've opened cars_text.php. It's identical to the page we set up in chapter one, apart from the label on the submit button. The command on line two includes the database query. I'm using the mySQLi version. Change it to the PDO version if you're using the SQLi database or any other database. The code we'll write in this page will be the same, whichever version you're using. If we scroll down to the bottom of the page, we can see that the name of the submit button is download, so we need to add a conditional statement to check for download in the post array when the submit button is clicked. So, let's go back above the doctype and add a new line after line two, then a conditional statement, if is set and what…

Contents