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

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.

Related

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'

Excel data are strange when MySQL column data has breaklines

I exported MySQL columns data into an excel file through the download concept using the header mechanisms. The problem is that if a column having text as its datatype has data containing breaklines like enumeration then the csv file is strange : the enumerated data are placed into different lines in the excel file. So how to make the data placed inside one cell ?
Here is the code of the download :
function downloadFile($outPut, $fileName){
$filesize = strlen($outPut);
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-type: text/enriched");
header("Content-length: $filesize");
header("Content-disposition: attachement; filename=$fileName");
ob_clean();
flush();
print($outPut);
exit();
}
My first suggestion would be to ensure that each of the fields you are exporting are within double quotes if they are not already, this will save a lot of formatting issues e.g. with commas within a field etc. If you are still having problems I would suggest trying to replace the newline characters with something that you will interpret as a new line (or just as space). Try this in your sql (around the field that ,ay have newline characters:
REPLACE(your_column_name,'\n',' ')
A dirty method is to use a "\r\n" as the actual row ending in the CSV file; and a simple "\n" as the breakline within a cell, making sure that you quote any cell values that contain the breakline.
$fh = fopen('test.csv', 'w+');
fwrite($fh, "sep=\t" . "\r\n");
fwrite($fh, 'A' ."\t" . 'B' . "\t" . 'C' . "\r\n");
fwrite($fh, 'D' ."\t" . "\"E\nF\nG\"" . "\t" . 'H' . "\r\n");
fclose($fh);
This example uses a tab separator between cells; and shows a three-line value in cell B2
EDIT
Or using fputcsv()
$fh = fopen('test2.csv', 'w+');
fwrite($fh, "sep=\t" . PHP_EOL);
fputcsv($fh, array('A', 'B', 'C'), "\t");
fputcsv($fh, array('D', "E\nF\nG", 'H'), "\t");
fclose($fh);

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

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

Print $name value in php

I am trying to print out the value of $name
yet it keeps printing out $name instead of the value here is the line:
header('Content-Disposition: attachment; filename="$name"');
PHP will only evaluate variables within double-quoted strings, not single quoted strings like you've used in your example.
Try this instead (if you need to output double quotes within a double-quoted string, you need to escape them with a backslash, otherwise PHP will treat them as the end-of-string delimiter):
header("Content-Disposition: attachment; filename=\"$name\"");
String interpolation does not happen between single quotes.
$name = "test";
echo "Value: $name"; // Value: test
echo 'Value: $name'; // Value: $name
More details here.
I think this is what your looking for
header('Content-Disposition: attachment; filename="'.$name.'"');
This would give a header like so:
Content-Disposition: attachment; filename="some_file_name.ext"
Hope this helps
Another way to do this is using sprintf
$header = sprintf('Content-Disposition: attachment; filename="%s"',$name);
header($header);
The sprintf is not really needed but there to show you how the variable would be placed into the header string
When dealing with single-quoted strings, always concatenate variables.
header('Content-Disposition: attachment; filename="' . $name . '"');
Try like this:
header('Content-Disposition: attachment; filename='.$name);
Why don't you just use " instead of ' like :
header("Content-Disposition: attachment; filename=$name");
header('Content-Disposition: attachment; filename='.$name);

Categories