Manikandan Thangaraj
Manikandan Thangaraj

Reputation: 1594

0's are truncate while write in to an csv using php function

I have try to write data to csv using the php function.

But the 0's are truncate while write in to an csv.

$data = array ( 'aaa,bbb,ccc,dddd', '000123,456,789','"aaa","bbb"');

$fp = fopen('data.csv', 'w');

foreach($data as $line)
{
  $val = explode(",",$line);
  fputcsv($fp, $val);
} 

fclose($fp);

Upvotes: 2

Views: 2398

Answers (3)

Rajasekar Gunasekaran
Rajasekar Gunasekaran

Reputation: 1827

if you are trying to open csv in excel or open office, it will truncate leading zeros. when u construct the string with "\t" before zero to avoid 0 truncation

Upvotes: 3

Jeremy
Jeremy

Reputation: 4975

I think Excel has treated it as a number and omitted the 0.

You may try to do this:

fputcsv ($fp, "='".$val."'");

See if it works

Upvotes: 2

James C
James C

Reputation: 14149

You could find that it's Excel, etc that's eating the 0 characters (you can test this out by opening the csv file in notepad (or whatever your favourite text editor is) and seeing if they're there.

If that's not the case then try using the following line:

fputcsv($fp, (string) $val);

Just in case the variable is somehow being cast to an integer somewhere.

Upvotes: 1

Related Questions