Zipcodes in CSV Generation

Like this blog? Consider exploring one of our sponsored banner ads...

When exporting to CSV format, then opening in a spreadsheet program like Excel zipcodes that start with a zero or zeroes have the preceding zeros stripped off. Obviously it is because the spreadsheet sees that column as integers and preceding zeros in integers are useless.

A quick and dirty trick to force Excel (hopefully you are using OpenOffice) to display the full zipcode, we wrap it in double quotes and put an equal sign in front of it, to force it to be a string like this:

$zipcode = 00123;
 
$data = '="' . $zipcode . '"' ;

So if you are doing the straight query to CSV export, using the fputcsv function it would look something like this. Basically just overwrite the value in the row and then continue along.

while ($row = mysql_fetch_assoc($query)){
 
	$row['zipcode'] = '="'.$row['zipcode'].'"';
 
	fputcsv($output, $row);
}

About this entry