0

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?

10
  • That's an issue with Excel, rather than your CSV, I suspect. Try looking at the file in Notepad to see what you're generating. Commented Apr 3, 2013 at 13:34
  • $cellphones .= '"' . $row["cellphone"] . '"' . "\r\n"; Commented Apr 3, 2013 at 13:35
  • @andrewsi I've already tried to export these numbers to a .txt file without a comma and it works perfectly. The problem appears when I try to export them to a .csv file as I explained. Commented Apr 3, 2013 at 13:38
  • @Amr - what's the difference between a .txt file and .csv file? Commented Apr 3, 2013 at 13:39
  • @andrewsi It's the client that wants the numbers in a .csv file Commented Apr 3, 2013 at 13:42

1 Answer 1

1

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";
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.