Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving numbers as a string in a csv

Tags:

php

csv

I am trying to put a column with a number with leading zeros into a csv file, but it keeps truncating the leading zeros, what can I do to keep them?

Here is the code I am using:

// fopen() here
function clean_zip($string){
    if(preg_match("/^\d{5,}/", $string)){
        $string = str_pad($string, 5, "0", STR_PAD_LEFT);
    }
    return $string;
}

while(($csv = fgetcsv($rhandle)) !== false){
    // other rows here
    $fcsv[9]  = (string)clean_zip($csv[9]);
    fputcsv($whandle, $fcsv);
}
like image 910
Get Off My Lawn Avatar asked Mar 25 '26 18:03

Get Off My Lawn


1 Answers

As already pointed out in the comments, wrapping a number with double quotes (") will result in something like "0123".

The way to go is adding a leading single quote (') as written down in the documentation:

If you decide to enter a number directly as text, enter an apostrophe (') first. For example, for years in column headings, you can enter '1999, '2000 and '2001. The apostrophe is not visible in the cell, it only indicates that the entry is to be recognized as a text. This is useful if, for example, you enter a telephone number or postal code that begins with a zero (0), because a zero (0) at the start of a sequence of digits is removed in normal number formats.

Source: Formatting Numbers as Text

The data is now parsed as a string, which results in it being ignored in a function.

Another way is to format the column as a text column.

like image 78
Sven Avatar answered Mar 28 '26 07:03

Sven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!