programing

fputcsv and integer typcasting to string

megabox 2023. 6. 8. 19:34
반응형

fputcsv and integer typcasting to string

So I have a line that I want to do a fputcsv on that has some integers (that I need to be treated as strings but they are numbers). These integers have leading zeroes that get cut off when I do the fputcsv but I don't want that to occur, is there any way around this? I tried just typcasting as (string) and putting my variable in quotations but the only way I have found so far is to just put quotes around the entire number which leads the quotation marks to be shown in the csv file when I open it up in excel, which I don't want to occur. Does anyone know of a way to get this to work? I think the fputcsv is just automatically assigning this variable a type for some reason and making it a integer or something...

EDIT Example Text:

What I fputcsv:

02305109

What I get in the csv file opened in excel:

2305109

but the leading zero is still there when I just use vi to open said csv file. Really strange.

I had the same problem for long numbers which I wanted as a string. Wrap it in single quotes and make it evaluable.

'="' . $yourNumber . '"'

Try prepending (or appending) your leading-zero integers with a null character.

$csv[0] = 02392398."\0";

Excel is interpreting the value as a number and formatting it as so. This has nothing to do with php.

This SU post has some information: https://superuser.com/questions/234997/how-can-i-stop-excel-from-eating-my-delicious-csv-files-and-excreting-useless-da

It is too simple my code is

//header utf-8
fprintf($fh, chr(0xEF).chr(0xBB).chr(0xBF));
fputcsv($fh, $this->_head);
$headerDisplayed = true;
//put data in file
foreach ( $this->_sqlResultArray as $data ) {
    // Put the data into the stream
    fputcsv($fh, array_map(function($v){
        //adding "\r" at the end of each field to force it as text
        return $v."\r";
    },$data));
}

output it as a formula, so as:

$line["phone"]= "=\"" .$line["phone"]. "\"";

You just need to add a quote to the beginning of the number:

'123456

and excel will not format this cell as a number.

Adding a single quote to the beginning of the data will solve the problem.

i.e '930838493828584738 instead of 930838493828584738 which converts to this 934E+n

If the csv file is provided by a third party, this could be a problem.

format the column using "00000000"

This has the advantage that it will preserve the format on save

Try a leading apostrophe (single quote). IIRC that keeps the leading zeros but doesn't appear in Excel.

ReferenceURL : https://stackoverflow.com/questions/11419319/fputcsv-and-integer-typcasting-to-string

반응형