PHP fputcsv() to create a CSV to import into outlook contacts

1.1k views Asked by At

I'm fetching values from a database and inserting them info a csv file to be downloaded and imported into outlook.

I'm using this code

// output headers so that the file is downloaded rather than displayed
$today = date("m.d.y");
header('Content-Type: text/csv;');
header('Content-Disposition: attachment; filename='.$today.'-allowners.csv');

// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');

// output the column headings
fputcsv($output, array('firstname', 'lastname', 'email'));

// fetch the data
$rows = mysql_query('SELECT first_name, last_name, email FROM owners');

// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);

And I'm getting weird results, first the column titles don't have delimiter, secondly not all fields from the database get delimited with ' " '. The output goes like this :

firstname,lastname,email
" aaaaa"," bbbbb",0000
" aaaaa"," bbbbb"," 0000"
"aaaaa ",bbbbb,[email protected]
 aaaaa,bbbbb,[email protected]
" aaaaa"," bbbbb"," [email protected]"
" aaaaa"," bbbbb"," [email protected]"

And when trying to import into outlook it's giving me an error stating that the file is invalid or in use by another aplication or process.

---------------Solution---------------

The problem was the linebreak ending of the file created with php running on linux to be opened in a windows system, this doesn't allways cause trouble in some software, but since it's MS Outlook they seem pretty strict. I tested opening the file with excel and Saved as CSV overwriting the existing file and it worked without a problem.

Solution can be found in the following url of an answer to other question.

http://stackoverflow.com/a/12723639/2633609
2

There are 2 answers

0
Halcyon On

The enclosures are not added because they're not needed. All values that are enclosed share the same trait: they have leading space.

Keep in mind that CSV is a very poorly defined format. Just about anything can be CSV. Delimiters, enclosures and escape characters are not well defined.

As for the error you're getting. Maybe Excel wants semi-colon separated files? Tab separated also seems to work sometimes. This depends on your language/regional settings.

3
Rob Baillie On

In the example output you've provided you don't have any formatting issues:

  • The fields that do not need enclosures (double-quotes) do not have double-quotes
  • The fields that DO need enclosures, have them
  • All fields in all rows have the required delimiter (comma)

The example given is a valid CSV output and in line with the documentation here: php.net/manual/en/function.fputcsv.php

The strongest suspicion is that the file isn't properly closed with an fclose at the end of your script.