How to fix "tabs" in Excel Export (PHP)? - php

I applied this solution to solve an encoding problem I got exporting files to .CSV and Excel and it worked successfully, but now another problem emerged:
The tabs ("\t") I use in PHP as the delimiter for Excel files stopped working. It was working before I solve the previous problem. When I open the excel file, it display likes:
"ColumnAColumbBColumnC" (all together).
If a export it like csv ('Content-type: text/csv; charset=UTF-8') I have success, but not as Excel (Content-type: application/vnd.ms-excel; charset=UTF-8).
Any solution for this?
Note: using "," as a separator is not a good solution for me, because I have values with "," in some fields.

The tabs ("\t") I use in PHP as the delimiter for Excel files stopped working.
Yes, that is correct.
Despite this there is still a simple way to export to Excel.
Use a table with <td> and <tr>, this does excel okay.
An example:
<?php
header("Content-Type: text/plain");
echo "<table border='1'>";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>First Name</th>";
echo "<th>Department</th>";
echo "<th>Date</th>";
echo "<th>Topic</th>";
echo "<th>State</th>";
echo "<th>E-mail</th>";
echo "<th>Place</th>";
echo "<th>Registration fee</th>";
echo '</tr>';
echo '</table>';
header("Content-disposition: attachment; filename=example_export_to_excel.xls");
}
?>
This works perfectly for export to excel.
There are no libraries needed, why look complicated things simple as it can.

If you have a comma in a string field and want to use a comma as a separator, then you enclose the string in quotes... that's how CSV files work.
So my assumption is that you aren't using PHP's built-in fputcsv() function to create your csv file, else you'd already know this... why not consider using it, because it handles all the little intricacies that you don't seem to be aware of.
Note that Excel csv files do use a tab, and are normally encoded as UTF-16LE with a BOM rather than as UTF-8; and there is no need to identify the charset in the content type header.

Related

Define new column data during PHP export

I was told that "\t" would 'tell' Excel that it is a new column data.
However, it is just an empty space and all my single line data are in ONE cell instead of seperate columns.
Did i do anything wrong?
while($row =mysqli_fetch_assoc($result))
{
$contents.=$row['idUsers']."\t";
$contents.=$row['First_Name']."\t";
$contents.=$row['Last_Name']."\t";
$contents.=$row['Email_Address']."\t";
$contents.=$row['Verified']."\n";
}
When you're creating a CSV file for MS Excel, you'll find that Excel's separator is locale specific, so what might work for one person won't necessarily work for another.
One way to try and force the issue is to use a sep=<x> line as the very first line of your CSV file; so if you initially define $content using
$contents = "sep=\t\n";
before starting your while loop, you may find that this allows MS Excel to correctly identify what separator you're using when the file you generate is loaded into Excel
And rather than "roll your own" csv format file, why don't you make use of PHP's built-in fputcsv() function, which will also handle quoting strings and generally simplify things for you
Have you tried the CSV format?
Replace your '\t' by a comma..
while($row =mysqli_fetch_assoc($result))
{
$contents.=$row['idUsers'].",";
$contents.=$row['First_Name'].",";
$contents.=$row['Last_Name'].",";
$contents.=$row['Email_Address'].",";
$contents.=$row['Verified']."\n";
}
http://en.wikipedia.org/wiki/Comma-separated_values

Make PHP exported CSV with UTF-8 character work on mac excel using commas

So I'm trying to export a csv using PHP in which the contents contains UTF-8 character and I want the resultant csv to open in Excel smoothly (including Mac excel)
So there is an answer here: How can I output a UTF-8 CSV in PHP that Excel will read properly?
Checkout the top answer.
But then in order to implement that you need to use tabs to separate the fields instead of commas...Is there a way to achieve this while still using commas and not tabs and still have it work in OS X
EDIT
Mostly to Mark Baker but everyone feel free to comment
Another code update
while(#ob_end_clean());
header('Content-Encoding: UTF-8');
header('Content-type: text/csv; charset=UTF-8');
header("Cache-Control: no-store, no-cache");
header("Content-Disposition: attachment; filename=fileexport.csv");
echo "\xEF\xBB\xBF";
print "sep=,\n";
print $output;
exit;
fputcsv should work fine in this instance. Take the following example, where as the third parameter of fputcsv is the delimiter. By default it is , (comma), but you could also use "\t" for tab files. CSV files should be interpreted the same on either OS
if( $fh = fopen("output_file.csv","w") ){
$put = array("column1, with comma","column2, with comma","column3" /*,"columnN"*/);
fputcsv($fh,$put,",");
fclose($fh);
}

Cell borders in excel with PHP

I'm using clean php to draw excel table:
$xls .= "Field\t\Cell1\t\Cell2\tCell3\r\n"
$xls .= chr(hexdec('FF')) . chr(hexdec('FE')) . $xls; //headers
echo $xls;
Is there any way to draw cell borders without using excel-library?
Excel has the knowledge to work with plain HTML tables. This will generate a warning from excel, but if you continue, it will show a table with border/colors/etc.
<?
header('Content-Type: application/vnd.ms-excel');
?>
<table border='1'>
<tr>
<td style='background-color:#f00;'>header</td>
<td style='background-color:#f00;'>header</td>
</tr>
</table>
If you really want to output an Excel file with almostly everything possible in Excel, you should use the following easy to use set of PHP classes:
http://phpexcel.codeplex.com/
No, you can't control formatting in a CSV file.
Excel accepts a multitude of formats though, so if you don't feel like breaking out phpexcel, you could create a SpreadsheetML file instead. It's a format quite similar to html and you can control a lot of formatting in there.

Sending php tags in a string

I've created a script which takes names from my db and for each name creates a .php file for them. However I would like to fill this file already with a (php) header since letters such as ë é and ú are not shown correctly without it.
So far i've got this:
<?php
// ...
while($row = mysql_fetch_array($res)){
$file = "Map/" . $row['name'] . ".php";
$fh = fopen("$file", "w+");
if($fh==false){
die("unable to create file");
}
echo "$file created <br/>";
$stringData = "<center><h1>". $row['name'] . "</h1></center>\n
No text available just yet.";
fwrite($fh, $stringData);
}
fclose($fh);
?>
What i would like to do now is place the following line of code even before the center tag:
<?php header('Content-Type: text/html; charset=ISO-8859-15'); ?>
As i retrieve the stored text from the .php file using an ajax request (with JQuery), the header must be in the file in order to be able to show those special letters. Thus my question: how can i place this line of code in each file, rather than php just executing it? (Or if this can be done easier, how so?)
Edit after comment:
After the script has run i would like to have a file that looks like this:
<?php header('Content-Type: text/html; charset=ISO-8859-15'); ?>
<center><h1>Chocolate</h1></center>
No text available yet.
You have to use meta tag in head section of your HTML, it tells the browser which character encoding is used:
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-15"/>
By the way, if you're starting a new project, think about using the UTF-8 encoding. It often is a better choise than ISO-* because it allows all Unicode characters (all characters of the whole world) with one encoding.
Try adding this, immediately after opening the file:
fwrite($fh, "<?php header('Content-Type: text/html; charset=ISO-8859-15'); ?>\n");
PHP is smart enough to know that ?> is not an end-PHP marker when it appears in a string literal.
Please ask about your real question; not about what you assume could be the solution. As far as I understood it the question should read something along: "How to set a specific file encoding via PHP?"
If your output is an HTML file use a META-tag as suggested by Glibnes.
If the written file is plain text, you should convert your text to UTF-8 and fwrite() it to the file.
Use the following stringData instead of the above
$stringData = '<?php header(\'Content-Type: text/html; charset=ISO-8859-15\'); ?><center><h1>'. $row['name'] . "</h1></center>\n
No text available just yet.";
As you are writing it in .php file. It should execute the header function.

PHP generate Excel/CSV file and send as UTF-8

I'm retrieving data from my Postgres DB in UTF-8. The db and the client_connection settings are in UTF-8.
Then I send 2 headers to the visitor:
header("Content-Type: application/msexcel");
header("Content-Disposition: $mode; filename=export.xls");
and start outputting plain text data in a CSV-manner. This will open as a simple Excel file on the visitors desktop.
$cols = array ("col1", "col2", "col3");
echo implode("\t", $cols)."\r\n";
Works fine, untill special characters like é, è etc are encountered.
I tried changing my client_encoding while retrieving the data from the db to latin-1, which works in most cases but not for all chars. So that is not a solution.
How could I send the outputted file as UTF-8? I don't think converting the data from the db to latin-1 is possible, since the char seems unknown in latin-1 ... so I need Excel to treat the file as UTF-8
I'd look into using the PHPExcel engine. It uses UTF-8 as default and it can generate a whole list of spreadsheet file types (Excel, OpenOffice, CSV, etc.).
I would recommend not sending plain-text and masquerading it as Excel. XLS files are typically binary, and while binary isn't required, the official Excel method of using non-binary data is to format it as XML.
You mention "CSV" in the title, but nothing about your problem includes anything related to CSV. I bring this up because I believe that you should actually change your tabs to commas, and then you could simply output a standard .csv file, which is read by Excel still but doesn't rely on undocumented or unstable functionality.
If you truly want to send application/msexcel, then you should use a real Excel library, because currently, you are not creating a real Excel file.
use ; charset=UTF-8 after aplication/xxxxxx I do use:
header("Content-Type: application/vnd.ms-excel; charset=UTF-8");
// header("Content-Length: " . strlen($thecontent)); // this is not mandatory
header('Content-Disposition: attachment; filename="file.xls"');
Try mb_convert_encoding function.
Try to use iconv, for converting string into required charset.
Have you tried utf8_encode() the string?
So something like: echo implode("\t", utf8_encode($cols)."\r\n")
Not sure if that would work, but give it a go

Categories