简体   繁体   中英

Exporting data from mysql table to a .csv file

I have a mysql table in which I store cellphone numbers of the users, and now I want to export only those numbers to a .csv file using php, and I don't want to use a comma in the end of each number. Now suppose I have the next 3 numbers stored in my table:

123456789
+966123456789  
00966123456789

Now if I used the next code:

$result = mysql_query("SELECT cellphone FROM user");
if ($result) {
    while ($row = mysql_fetch_array($result)) {
        $cellphones .= $row["cellphone"] . ",\r\n"; //note the comma here
    }
}

$filename = "cellphones_" . date("Y-m-d_H-i");
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=" . $filename . ".csv");
print $cellphones;
exit;

I will get a .csv file in which I have the numbers like this:

+966123456789,
00966123456789,
123456789,

But if I used the same code without the comma like this:

    $cellphones .= $row["cellphone"] . "\r\n";

instead of:

    $cellphones .= $row["cellphone"] . ",\r\n"; //note the comma here

then numbers in the .csv file will be:

9.66123E+11
9.66123E+11
123456789

So what is the wrong and how can I get the numbers appear correctly without the comma?

Explanation

The comma is being treated as part of the value in each line, so MS Excel treats the data as a string when it imports.... meaning that it will be stored in the cell "as is". Without the comma, MS Excel treates the value as a number, using general formatting which doesn't display leading zeroes, and which switches to scientific format if the number exceeds a defined number of digits.

Solution

In order to always treat the value as a string, without the comma, enclose the value in double quote marks.

$cellphones .= '"' . $row["cellphone"] . '"' . "\r\n";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM