Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member
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 that expects a string.
The first one will be Content-Type, then a colon and the mine type which is text/csv. Another header, this one will be Content-Disposition, and after that, colon Attachment and a semicolon file name equals. We'll call this cars dot CSV. So that's the file name we created when we download the file.
We need three other headers to prevent the browser from caching the data, and to save time I'm going to copy the mailer from the text file that you can find at the exercise files for this video. The firs one Cache-Control makes no cache the second one, Pragma: no-cache is the same as Cache-Control except it's used by older browsers and then the last one Expires:0, tells the browsers that it needs to create a new file each time. Rather than create a file on the server, we can stream the output directly using the F open function.
So the F open function returns a handle that needs to be passed to other functions that write the file. So we'll create that handle; we'll call it csvoutput, then fopen, and the first argument in quotes php://output. And this will send the output directly to the browser. And the second argument needs to be the mode, which is right, so in quotes w. With the stream open, we need to get the first row from the database result.
I'm going to use the get row custom function that was defined in chapter one, this will work with both mySQLi and with PDO. And we pass that the result which is stored as result and this is an associate of array that uses the database column names as the name of each array element. So we can use the column names as the headers for our CSV file. So to get the column names, we'll use the array keys function, and we'll store the value in headers, and we can then output those headers to our CSV file with the fputcsv function, so fputcsv, that expects the handle; which we've called csvoutput.
And then we just pass the headers. By default fputcsv uses commas to separate the fields and double quotes to enclose fields that contain spaces, commas or quotes. If you want to change those there are optional third and fourth arguments which let you choose a different separator and enclosure character, but we are going to leave it like that. We need to pass the same row to fputcsv otherwise we are going to lose the values in the first row of the database results.
And this time, we pass it, row, so we're just getting the values this time. All that remains is to loop through the rest of the database result to add the remaining rows to the file. We need a while loop, and then while row = getRow. Pass it the result. And then in the fputcsv, and our handle is csvoutput. And we just pass it the row. And once we've got to the end of our database result, we need to close the stream.
So fclose. And the handle again, csvoutput, and finally, exit. So we can now save that page and test it in a browser. So let's go to a browser. There is cars_text and I need to change that URL to cars_csv.php. Load that. There's the database result being displayed. We go down to the bottom.
Download results in CSV format. Click Download File. There it is, cars.csv has been downloaded, and if I click that to open it, because I have Excel installed on my machine, it automatically opens in Microsoft Excel. There on the first row are the column headers And then there are all the values in the different fields. If you don't have Excel on your machine, you can open it in an ordinary text editor. Let's just go to my downloads folder.
And there it is cars.csv. If I right click on that, and edit with Notepad++. There it is. It's opened as an ordinary text file. You can see that there are commas between each field. And then fields that contain spaces or other characters, they're enclosed in double quotes. So exporting data to a CSV file is a quick and easy way to distribute data that's suitable for display as a spreadsheet. As you've just seen, it opens automatically in Microsoft Excel if it's installed on your system.
It's also easy to import into Open Office Calc or into a database. The main drawback is that there's no formatting. We will look at more sophisticated spreadsheet exports later.
Get unlimited access to all courses for just $25/month.Become a member
82 Video lessons · 101341 Viewers
61 Video lessons · 88099 Viewers
71 Video lessons · 71950 Viewers
56 Video lessons · 103769 Viewers
Access exercise files from a button right under the course name.
Search within course videos and transcripts, and jump right to the results.
Remove icons showing you already watched videos if you want to start over.
Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.
Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.
Your file was successfully uploaded.