2

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);
3
  • 5
    I think your application removes them, not your code. Excel for instance, attempts to recognize data types and parse them the way it suits best. Commented Jul 28, 2011 at 11:00
  • It might help to treat the numbers as strings: '"000123","456","789"' Commented Jul 28, 2011 at 11:03
  • I try this '"000123","456","789"', but the Quotes are displayed in the excel cell... Commented Jul 28, 2011 at 11:50

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

This is susceptible to errors if the value contains quote characters.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.