1

I have a link on a page that, when clicked, exports an array of data to csv using fputcsv. When Excel displays the data, there is a column that looks like an integer, but it's not, and Excel is converting it to scientific notation. How do I export the data so that this column is displayed as characters (not a scientific number) ?

The code I'm using for export is from Alain Tiemblo's answer here: Link to Code

function array2csv(array &$array)
{
   if (count($array) == 0) {
     return null;
   }
   ob_start();
   $df = fopen("php://output", 'w');
   fputcsv($df, array_keys(reset($array)));
   foreach ($array as $row) {
      fputcsv($df, $row);
   }
   fclose($df);
   return ob_get_clean();
}
Community
  • 1
  • 1
devlin carnate
  • 8,309
  • 7
  • 48
  • 82

4 Answers4

1

Not sure about Excel, but LibreOffice and OpenOffice will import fields as strings if the CSV field is quoted. For example, you want your CSV to be something like:

foo,bar,"12345",baz

(You may also have to check "Quoted field as text" option in the file open dialog.)

Edit: PHP's fputcsv() function will only use quote wrappers if it needs to, so you'll likely have to manually force quotes around the actual field value yourself:

$field = 12345;
$quoted_field = '"' . $field . '"';

Edit 2: If you don't need to worry about escaping, this might work for you instead of fputcsv():

fwrite($fp, '"' . implode($fields, '","') . '"' . "\n");
Alex Howansky
  • 50,515
  • 8
  • 78
  • 98
0

Try to force your int into a string before your fputcsv.

For example

$foo = "$foo";

http://php.net/manual/en/language.types.type-juggling.php

But then again Excel might make up its own mind when converting your CSV to an Excel format...

Also this question might help: Excel CSV - Number cell format

Community
  • 1
  • 1
Nathan H
  • 48,033
  • 60
  • 165
  • 247
0

You could cast the value to string using strval.

Thomas
  • 1,401
  • 8
  • 12
0

converting integer to string using :- string, strval or enclosing value in double/single quotes , or even concat space with the variable does not work because CSV doesn't hold field type information.

The only way I found is to add some character or symbol to forcefully make it string but that will show in output too.