Exporting data from mysql table to a .csv file - php

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";

Related

csv_output containing with field . (full stop)

I have a php script that is generating a tab delimited .txt file that works great but I need to output a field that contains a . (full stop/ period) within the $model field i.e itemname.1 it affects the formatting of the file.
$csv_output .= $model . "\t";
$csv_output .= '' . "\t";
$csv_output .= '' . "\t";
$csv_output .= '' . "\t";
$csv_output .= $totalstock . "\t";
$csv_output .= $leadtime . "\t";
$csv_output .= "\n";
$csv_handler = fopen('../outputfile.txt','w');
fwrite ($csv_handler,$csv_output);
fclose ($csv_handler);
I have tried enclosing in double quotes and various other variations but the output is inserting newlines
example output
itemname.1
20 1
any ideas how i can output the fields with the . in them without it affecting the tabs/lines.
Could you show us your code that encloses the variable in quotes please?
The not-very-well-informed solution appears to be use replace() to test if the . is indeed causing the new line, or if it's "something else". You might just be able to replace new line straight up even.
It Was a school boy error.
The issue was the data imported into db had carriage returns on each line entry, although the data appeared correct in the db and in excel the problem only manifested in the output file.
Thanks for your help guys made me go back to source and identify the issue.

CSV Export via PHP isn't separating to columns on MS Excel

I can't for the life of me figure this out at the moment but watch it be something blatantly obvious.
CSV Exports are working and are comma delimited. But MS Excel is refusing to column them correctly.
I have the headers like so:
header('Content-Encoding: UTF-8');
header("Content-type: text/csv; charset=UTF-8");
header("Content-Disposition: attachment; filename=" . $filename . ".csv");
And the code like so:
$contents = "Artist,Title,Presenter,Time Played\n";
while ($row = mysql_fetch_array($user_query)) {
$contents.= "\"" . $row['artist'] . "\",";
$contents.= "\"" . $row['title'] . "\",";
$contents.= "\"" . $row['presenter'] . "\",";
$contents.= "\"" . $row['timeplayed'] . "\"\n";
}
$contents_final = chr(255) . chr(254) . mb_convert_encoding($contents, "UTF-16LE", "UTF-8");
print $contents_final;
And it seems to work fine on my MS Excel machine, but I have used this machine for a lot of manual CSV work so it may be a change I've made there. For first installs, it's not separating by columns properly.
It still needs to be a CSV file though as a requirement.
Any thoughts on how I can force Excel to read this properly without the user having to manually force the columns?
For separate in columns use '\t' and for separate rows use '\n'

adding white space between clean string functions

I've got the following code which outputs two different strings sent from a php contact form.
$email_message .= "Module: ".clean_string($modcode_1_from)."\s".clean_string($modcode_2_from)."\r\n";
is meant to display module code 1 and module code 2.
Currently looks likes this
1001\s2002
However i want it to look like:
1001 2002
So i added \s to add white space between the strings but it does not do anything for me.
use non-breaking space or you can use \t to add a tab char. And the best one is just a space:
$email_message .= "Module: " . clean_string($modcode_1_from). " ". clean_string($modcode_2_from) . "\r\n";
$email_message .= "Module: " . clean_string($modcode_1_from) . "\t" . clean_string($modcode_2_from) . "\r\n";
$email_message .= "Module: " . clean_string($modcode_1_from) . " " . clean_string($modcode_2_from) . "\r\n";
You can use this:
$email_message .= "Module: ".clean_string($modcode_1_from)." ".clean_string($modcode_2_from)."\r\n";
What I did: I removed the \s and put a space in its place.
IMPORTANT NOTE: DO NOT USE " ", it will echo/add between 1001 and 2002.
Resulting in:
1001 2002
Therefore, replace \s with an actual space using your spacebar.
Footnote (other options):
If you wish to later use your data in Excel for example, you could use a comma ,
(CSV, comma seperated value) as the seperating character or a tab for a tab-seperated value \t i.e. "\t", or a semi-colon ; i.e. "; ".
You may need/want to add a space after the comma; i.e. ", " for use as a CSV.
Example output of using a comma: 1001, 1002.
Can you try changing the \s to
' '
and see if this works for you?
Try this,
$email_message .= "Module: ".clean_string($modcode_1_from)." ".clean_string($modcode_2_from)."\r\n";

Output double quote to csv file from PHP

I know there are some similar threads but my code doesn't look anything like those questions and am not sure how to adopt. I think my approach can probably work, but I am just not getting the desired result.
I am trying to export a MySQL db to a csv file. One field has commas in it so putting the string in double quotes allows me to reimport the csv file back into my program. Without the quotes, the comma makes it seem like another field, so then all subsequent data is off in my reimport.
The first line of code outputs perfect, the description field may have commas or other punctuation. I want to put double quotes around it and have it output to my csv file.
<td><?php echo $rows['model']; $csv_output .= $rows['model'] . ", ";?></td>
<td><?php echo $rows['description']; $csv_output .= "\"" . $rows['description'] . "\"" . ", ";?></td>
For testing I have substituted "\"" with "5" and a 5 appears before and after my string and in the csv file.
I am new so if it is at all possible to do it this way, it would be better than changing my approach.
I tried the below line and added an echo to the screen and all my data, quotes included displays.
<td><?php echo $rows['description']; $csv_output .= '"' . $rows['description'] . '"' . ", ";?></td>
So one complete line looks like this.
1, 1, , , "Retiremnet Costs JE 100209 - F", 388155, 0, 1, , , 2006-06-30, A, 1, 0, 0, 113687.67, , ,
The quotes are there.
But when I press a button to post to the next page where the file will be written, the data disappears and leaves me with this.
1, 1, , ,
So it seems to me that there is something perhaps wrong with the file that writes the data so I'll include that.
<?php
$out = '';
if (isset($_POST['csv_hdr'])) {
$out .= $_POST['csv_hdr'];
$out .= "\n";
}
if (isset($_POST['csv_output'])) {
$out .= $_POST['csv_output'];
}
$filename = $file."_".date("Y-m-d_H-i",time());
//Generate the CSV file header
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
//Print the contents of out to the generated file.
print $out;
//Exit the script
exit;
?>
I figured out the problem but still don't have a solution. If I put in
$out .= "4, 1, , , \"Cisco 1000Base-SX SFP, LC\", 708476, 0, 3, , , 2011-03-15, A, 1, 20016525, 7088398, 300.00, , , ";
The file writes perfectly. I changed all of my csv_output statements so that when I echo it reads exactly the same as what I pasted over the POST variable on the POST page, but when I do that, the csv_output variable is completely empty.
Thanks

Issue with control chars - PHP does not print \t (tab character)

i'm sending an XLS file with the header. Everything is working fine. But when i tell it to print the tab to separate the cells in the XLS by print \t. It does not prints the tab. It just prints the '\t' in the file and when i download the XLS file everything that should be in different cell is all in one cell with text like:
val1\tval2\tval3\t
Those three values should be separate in their separate cells.
i have been trying for 2 hours now nothing is working :(.
i send headers like this:
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$filename.$fileextention);
header("Pragma: no-cache");
header("Expires: 0");
and just print the values like
echo $val1 . '\t' . $val2 . '\t' . $val3;
i have tried using single or double quts. and print and echo both buy still :(
Try this (see quotes)
header('Content-type: application/vnd.ms-excel');
echo "val1\tval2\tval3";
I'm quite sure that quotes cause the issue.
echo $val1 . "\t" . $val2 . "\t" . $val3;
should do the thing. Just look at this:
<?php
echo 'Test\tTest';
echo "\r\n";
echo "Test\tTest";
echo "\r\n";
which outputs:
Test\tTest
Test Test
Use double quotes when you need control chars.
Hopefully this can solve your problem.
Use double quotes: "\t". Within single quotes only \\ and \' is recognised.
This should work:
echo $val1 . "\t" . $val2 . "\t" . $val3;
If it doesn't, it's a bug in PHP.

Categories