Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Outputting the result as a CSV file

From: Exporting Data to Files with PHP

Video: Outputting the result as a CSV file

Downloading data to a CSV file is a The code on line two includes the database result.

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 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.

Show transcript

This video is part of

Image for Exporting Data to Files with PHP
Exporting Data to Files with PHP

44 video lessons · 2420 viewers

David Powers

Expand all | Collapse all
  1. 5m 57s
    1. Welcome
    2. What you should know before watching this course
      2m 42s
    3. Using the exercise files
      2m 16s
  2. 28m 3s
    1. Loading the test data into a database
      4m 8s
    2. Querying the database with MySQL Improved
      6m 4s
    3. Connecting to different databases with PHP Data Objects (PDO)
      2m 26s
    4. Querying the database with PDO
      7m 47s
    5. Displaying the data in a webpage
      5m 1s
    6. Autoloading classes
      2m 37s
  3. 38m 47s
    1. Outputting the database result to a text file
      6m 32s
    2. Outputting the result as a CSV file
      6m 53s
    3. Introducing the Base class for file downloads
      4m 37s
    4. Using the Text class for greater control over output
      7m 20s
    5. Controlling CSV options with the Csv class
      6m 49s
    6. Saving the data to a local file
      6m 36s
  4. 51m 42s
    1. Introducing PHPExcel
      3m 31s
    2. Setting properties and defaults in PHPExcel
      6m 58s
    3. Setting the spreadsheet's print options
      5m 59s
    4. Populating an Excel spreadsheet with data
      7m 46s
    5. Formatting columns in PHPExcel
      5m 47s
    6. Downloading the data as a .xlsx file
      5m 18s
    7. Creating a spreadsheet in the OpenDocument format
      3m 4s
    8. Creating columns and headers in Fusonic SpreadsheetExport
      6m 27s
    9. Adding the data and downloading as a .ods file
      6m 52s
  5. 22m 10s
    1. Installing PHPRtfLite
      3m 27s
    2. Defining the page margins and the footer
      6m 55s
    3. Setting heading and paragraph styles
      5m 18s
    4. Adding the data and outputting a .rtf file
      6m 30s
  6. 16m 35s
    1. Understanding the basic process
      3m 52s
    2. Merging XML documents with XSLT
      4m 13s
    3. Preparing a directory to generate the output
      1m 48s
    4. Generating XML from a database result
      6m 42s
  7. 27m 17s
    1. Creating a .odt file to use as a template
      4m 29s
    2. Inspecting the structure of an OpenDocument text file
      2m 43s
    3. Extracting the main content file from a .odt document
      5m 2s
    4. Converting the main content file to XSLT
      8m 3s
    5. Outputting the database result as a .odt file
      7m 0s
  8. 29m 0s
    1. Creating a .docx file to use as a template
      3m 37s
    2. Extracting the main content file from a Word document
      5m 28s
    3. Formatting the main content file
      3m 38s
    4. Converting the main content file to XSLT
      6m 18s
    5. Outputting the database result as a .docx file
      6m 4s
    6. Offering a choice of download formats
      3m 55s
  9. 3m 25s
    1. Goodbye
      3m 25s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.

Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.

Mark all as unwatched Cancel


You have completed Exporting Data to Files with PHP.

Return to your organization's learning portal to continue training, or close this page.

Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

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.

Are you sure you want to delete this note?


Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.