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
Related
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.
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'
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";
I am putting together a string that I will output to a .srt file:
while ($row = mysql_fetch_array($res)) {
$srt = $srt . $row['line_number'] . PHP_EOL;
$srt = $srt . str_replace(".", ",", $row['start']) . " --> " . str_replace(".", ",", $row['end']) .PHP_EOL ;
$srt = $srt . br2nl($row['text']) . PHP_EOL;
$srt = $srt . PHP_EOL;
}
But it seems like PHP_EOL isn't working, because my output is:
100:00:02,107 --> 00:00:05,810you sure
and doesn't have any newlines. I am trying to get my output to be:
1
00:00:02,107 --> 00:00:05,810
you sure
followed by a newline.
It works when testing through localhost on my computer. Could the PHP version on my host be missing support for PHP_EOL?
The PHP manual says the PHP_EOL constant was available since PHP 4.3.10 and PHP 5.0.2
PHP_EOL (string)
The correct 'End Of Line' symbol for this platform. Available since PHP 4.3.10 and PHP 5.0.2 - http://php.net/manual/en/reserved.constants.php
So test to see if it exists:
var_dump(PHP_EOL); // should output: string(1) " "
OR
var_dump(defined("PHP_EOL")); // should output if exists: bool(true)
and if it is not defined, just define it manually if you want
define("PHP_EOL", "\n");
OR just use echo "\n" or echo "\r\n"
The other possible reason is when you output the $srt variable in your browser your outputting and the mime type is set in HTML and so you see it as one line, but if you view the source it should be spanned accross multiple lines.
To ensure text output you could echo out a <pre> tag if you want to keep html or at the top of your php file add this line to force text output:
header('Content-Type: text/plain', true);
PHP_EOL The correct 'End Of Line' symbol for this platform.
So it works on local host because its window and gives a windows line break
You online website is probably on linux and gives a linux line-break
To get a consistent result use "\r\n" instead of PHP_EOL, although I think media players will be a ble to recognize any style of line breaks.
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.