Set character coding when generating xls file with php - php

How can I set UTF8 character coding with this code?
My problem is that when I open the exported file in Excel, I have to set the encoding manually.
$filename = "termekek.xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
$result = mysqli_query($kapcs, $sql) or die('SQL error - '.mysqli_error($kapcs));
while($row = mysqli_fetch_assoc($result))
{
if(!$flag)
{
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
array_walk($row, __NAMESPACE__ . '\cleanData');
echo implode("\t", array_values($row)) . "\r\n";
}
exit;

You need to send a UTF8 BOM (Byte Order Mark) after sending your headers and before the data:
$filename = "termekek.xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
echo "\xEF\xBB\xBF"; // UTF8 BOM
$flag = false;
$result = mysqli_query($kapcs, $sql) or die('SQL error - '.mysqli_error($kapcs));
while ($row = mysqli_fetch_assoc($result)) {
if (!$flag) {
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
array_walk($row, __NAMESPACE__ . '\cleanData');
echo implode("\t", array_values($row)) . "\r\n";
}
exit();

Related

Export unicode data to excel in php

İ can export json data to excel with PHP. But I use ə,ü,ç,ı,ö and so on. This caracters don`t show.
My code:
$file = "website_data_" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename=\"$file\"");
header("Content-Type: application/vnd.ms-excel; ");
$flag = false;
foreach($output as $row) {
if(!$flag) {
$arr = implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
array_walk($row, __NAMESPACE__ . '\cleanData');
$arr = $arr.implode("\t", array_values($row)) . "\r\n";
}
echo $arr;
Help me please
Change the header to
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
to enforce using the UTF-8 character set.
When this does not work, please show what your filter does.

Wordpress - export a mysql table to csv with column headers

I am able to download a file in csv format for my table , but how to add column headers to the same file .
The current code is following -
// load wpdb
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-load.php';
global $wpdb;
$table = $_POST["table_name"];// table name
$file = 'database_csv'; // csv file name
$results = $wpdb->get_results("SELECT * FROM $wpdb->prefix$table",ARRAY_A );
if(count($results) > 0){
foreach($results as $result){
$result = array_values($result);
$result = implode(", ", $result);
$csv_output .= $result."\n";
}
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
header("Pragma: no-cache");
header("Expires: 0");
print $csv_output;
exit;
I was able to do it by first getting column names and then assigning it to final output :
$table_name = $wpdb->prefix.$_POST["table_name"];// table name
$file = 'database_csv'; // csv file name
$results = $wpdb->get_results("SELECT * FROM $table_name",ARRAY_A );
// get column names
$query = "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='".$wpdb->dbname."' AND `TABLE_NAME`='".$table_name."'";
$columnNamesList = $wpdb->get_results($query);
foreach ( $columnNamesList as $column_name ) {
$csv_output.=$column_name->COLUMN_NAME.",";
}
// remove last additional comma
$csv_output = substr($csv_output,0,strlen($csv_output)-1);
// start dumping csv rows in new line
$csv_output.="\n";
if(count($results) > 0){
foreach($results as $result){
$result = array_values($result);
$result = implode(", ", $result);
$csv_output .= $result."\n";
}
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
header("Pragma: no-cache");
header("Expires: 0");
print $csv_output;
exit;

File download does not start with JQuery

I'm trying to start the download of a file using JQuery. The file is created by a .php function.
The download DOES NOT start. It starts only if i open the .php file MANUALLY (commenting the isset and writing the data manually into the file).
This is the JQuery code:
$("#experimenter_dataset").click(function() {
var imei = $("#select_download_experimenters option:selected").text();
$.post("download_imei_activities.php", { imei:imei }).done(function( data ) {
});
});
This is the php code
if(isset($_POST["imei"])) {
$imei = $_POST["imei"];
$stmt = $pdo->prepare("SELECT * FROM performedactivity WHERE experimenter=:imei");
$stmt->bindParam(":imei", $imei, PDO::PARAM_STR);
//$output = $imei . ".txt";
$output = "";
if ($stmt->execute()) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$activity = $row["activity"];
$timestamp_start = $row["timestampstart"];
$timestamp_stop = $row["timestampstop"];
$date_hour_start = explode(" ", $timestamp_start);
$date_hour_stop = explode(" ", $timestamp_stop);
//$current = "";
$output .= $date_hour_start[0] . "\t" . $date_hour_start[1] . "\t" . $activity . "\t" . "START" . "\r\n";
$output .= $date_hour_stop[0] . "\t" . $date_hour_stop[1] . "\t" . $activity . "\t" . "END" . "\r\n";
//file_put_contents($output, $current, FILE_APPEND | LOCK_EX);
}
} else {
//echo json_encode($pdo->errorInfo());
}
// We'll be outputting a text file
header("Cache-Control: public");
header("Content-Description: File Transfer");
header('Content-type: text/plain');
header('Content-Disposition: attachment; filename='.$imei . ".txt");
header("Content-Transfer-Encoding: binary");
print($output);
//echo $output;
/*header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename= " . $output);
header("Content-Transfer-Encoding: binary");
readfile($output);*/
} else {
//echo "imei parameter is missing";
}

No graphical side to PHP script

So I have this piece of code here I got off the internet, it's supposed to export data from mySQL database to an excel file.
The thing is that how am I supposed to trigger this? There's no graphical side of this, no button to trigger the script, nothing.
How can I make it work?
<?PHP
// Original PHP code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
include('config.php');
function cleanData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "website_data_" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
$result = pg_query("SELECT * FROM norse5_proov ORDER BY id") or die('Query failed!');
while(false !== ($row = pg_fetch_assoc($result))) {
if(!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
array_walk($row, 'cleanData');
echo implode("\t", array_values($row)) . "\r\n";
}
exit;
?>
Here's some code that works for me in a commercial app;
if($_REQUEST["EXCEL"]){
header("Content-Type: application/excel");
header("Content-Disposition: attachment; FileName=assets.xls");
header("Cache-Control: private");
header("Content-Length: ".strLen($data));
echo $data;
exit;
}
The $data is tab delimited text, but the excel headers open Excel and imports the text

CSV export without MYSQL FILE functions

i'd like to make an export into CSV format, but the mutualised host i use has deactivate the FILE functions in mysql.
I did a simple SELECT and then a fopen and fwrite with PHP.
The problem is that in fields there is carriage returns or double quotes.
How to keep them and build a correct csv file?
Thanks a lot.
To build a best CSV. you can do following way.
$filename ='data.csv';
$csv_terminated = "\n";
$csv_separator = ",";
$csv_enclosed = '"';
$csv_escaped = "\\";
$results = array('1','2','3');// value
$schema_insert = '';
$header = array('a','b','c');// header
for ($i = 0; $i< count($header); $i++)
{
$l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
stripslashes($header[$i])) . $csv_enclosed;
$schema_insert .= $l;
$schema_insert .= $csv_separator;
} // end for
$out = trim(substr($schema_insert, 0, -1));
$out .= $csv_terminated;
// Format the data
for($i=0;$i<count($results);$i++)
{
$row = $results[$i];
$schema_insert = '';
for ($j = 0; $j < count($header); $j++)
{
if ($row[$j] == '0' || $row[$j] != '')
{
if ($csv_enclosed == '')
{
$schema_insert .= $row[$j];
} else
{
$schema_insert .= $csv_enclosed .
str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
}
} else
{
$schema_insert .= 'NULL';
}
if ($j < count($header) - 1)
{
$schema_insert .= $csv_separator;
}
} // end for
$out .= $schema_insert;
$out .= $csv_terminated;
} // end while
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Length: " . strlen($out));
// Output to browser with appropriate mime type, you choose <img src="http://thetechnofreak.com/wp-includes/images/smilies/icon_wink.gif" alt=";)" class="wp-smiley">
header("Content-type: text/x-csv");
//header("Content-type: text/csv");
//header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=$filename");
echo $out;
Notice that,
+ when you make enclosed for description which has html code , you should use double quote.
+ Empty value --> Change to Null text or Zero value
They will make your CSV better.
You can download file.csv by use header()
Output everything you want (base on csv format) after header function, for example:
$filename = "output";
header('Content-Type: text/csv');
header('Content-disposition: attachment;'.$filename.'=.csv');
$separate = ","; //or ;
$endline = "\r\n";
foreach($data as $key => $item)
{
echo $key.$separate.$value.$endline;
}
protected function getCsv( $fileName, array $data )
{
// alot of headers here, make force download work on IE8 over SSL
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: application/octet-stream");
header('Content-Disposition: attachment; filename="'.$fileName.'"');
header("Content-Transfer-Encoding: binary");
// Joe Green says:
// based on http://www.php.net/manual/en/function.fputcsv.php#100033
$outStream = fopen("php://output", "r+");
function __getCsv( &$vals, $key, $filehandler ) {
fputcsv( $filehandler, $vals, ',', '"');
}
array_walk( $data, '__getCsv', $outStream );
fclose($outStream);
}
fputcsv is your friend. Also, I had to refine this function to get it to this point. Some of those headers are required by IE to force the csv to open as a csv, particularly over SSL. I seem to recall it had something to do with IE8 not recognising the 'text/csv' content type in the first instance and some security features around SSL downloads in the second.

Categories