By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

Creating Excel Compatible Files

How to make .csv files that can be importet into microsoft excel or OpenOffice.

Edited: 2013-01-19 12:26

One of the easiest ways to import data into Excel or OpenOffice Calc, is through the use of .csv files. A .csv file is just a comma or semicolon separated list of values, used to store tabular data – hence the name comma-separated values (.csv) – it is therefor very easy to write to these files with your favorite programming or scripting language. In this tutorial we will be looking into how we can write these files.

When mining data – often by crawling web pages – using .csv files can provide an easy way to present the data visually.

The following example shows the format of a .csv file, this file consists of three rows – one per line – and a heading for each column. The first row contains the headings for the columns. You can easily add more rows, just remember the "one row per line" rule. You should make sure that each row have the same number of columns, otherwise you might end up "pushing" data to columns where they do not belong.


Writing Csv files with PHP

In this Tutorial, we will be using semicolon as column separator, but you may want to use something else, in case semicolon will appear in the data you collect. Another way to get around the problem, may be to surround each field value in quotes.

Writing rows and columns to a file can easily be done using a simple loop, in PHP this will look somewhat like the below code example:

$stringFileContent = 'Column 1;Column 2;Column 3';  // Column format
$number = 0;
while ($number < 10) {
  $stringFileContent .= $number . ";"; // Column 1
  $stringFileContent .= $number . ";"; // Column 2
  $stringFileContent .= $number; // Column 3
  $stringFileContent .= "\n"; // Next Row

The above example is just using the counter to fill out the fields in the file, you can easily modify the script to match your own requirements.

See also

  1. While and For Loops in PHP
  2. Create and Write to Files With PHP
  3. Read Files With PHP