Exporting MySQL data to Excel - php

I have been looking for ways to export my data to an Excel spreadsheet. I have tried loads of examples and have been unsuccessful. This is my current code that returns, "Query Failed!". when changing the "ORDER BY" however, the spreadsheet returns the data but loops an error underneath. This is the code ive found and am using:
$con = mysql_connect($hostname,$username,$password,$db_name) or die('Could not connect: ' . mysql_error());
function cleanData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
$filename = "website_data_" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-type: application/vnd.ms-excel; charset=UTF-16LE");
$flag = false;
$result = mysql_query("SELECT * FROM test ORDER BY field") or die('Query failed!');
while(false !== ($row = mysql_fetch_assoc($result)))
{
if(!$flag)
{
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
array_walk($row, 'cleanData');
echo implode("\t", array_values($row)) . "\r\n";
}
Can anyone tell me why this happens?
(The same thing happens using mysqli functions too)

Related

All fields are showing in one column when exporting mysqli data to excel using php

I have written a simple php script for download excel file which contain some MySQLI data fetching by a MySQLI query, it was working fine when I was using English data but when I used utf 8 language such as Arabic, it shows all the data in one column in the excel file,
here is the code, any help will be appreciated.
<?php
$conn = new mysqli('localhost', 'root', '');
mysqli_select_db($conn, 'test_db');
mysqli_query($conn, "set names 'utf8'");
setlocale(LC_ALL, 'en_US.UTF-8');
$sql = "SELECT `user_name`,`user_q1`,`user_q2`,
`user_q3`,`user_q4`,`user_q5`
FROM `usertable`";
$setRec = mysqli_query($conn, $sql);
$columnHeader = '';
$columnHeader = "الاسم" . "\t" . "الاجابة 1" . "\t" . "الاجابة 2" . "\t". "الاجابة 3" . "\t". "الاجابة 4" . "\t". "الاجابة 5" . "\t";
$setData = '';
while ($rec = mysqli_fetch_row($setRec)) {
$rowData = '';
foreach ($rec as $value) {
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData) . "\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=User_Detail.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo ucwords($columnHeader) . "\n" . $setData . "\n";
?>

How to export to excel in Arabic?

I am trying to export Arabic data from MySQL to Excel, but I get weird symbols,
like this: كرة
Here is my code:
<?php
$conn = new mysqli('localhost', 'root', '');
mysqli_select_db($conn, 'crud');
mysqli_query($conn, "set names 'utf8'");
$sql = "SELECT `userid`,`first_name`,`last_name` FROM `employee`";
$setRec = mysqli_query($conn, $sql);
$columnHeader = '';
$columnHeader = "User Id" . "\t" . "First Name" . "\t" . "Last Name" . "\t";
$setData = '';
while ($rec = mysqli_fetch_row($setRec)) {
$rowData = '';
foreach ($rec as $value) {
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData) . "\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=User_Detail.xls");
header("Pragma: no-cache");
header("Expires: 0");
echo ucwords($columnHeader) . "\n" . $setData . "\n";
?>
How can I properly export this data?
According to this answer, the only encoding that seems to work consistently is UTF-16LE with a BOM. Try editing your code accordingly:
<?php
$conn = new mysqli('localhost', 'root', '');
mysqli_select_db($conn, 'crud');
mysqli_query($conn, "set names 'utf8'");
$sql = "SELECT `userid`,`first_name`,`last_name` FROM `employee`";
$setRec = mysqli_query($conn, $sql);
$columnHeader = '';
$columnHeader = "User Id" . "\t" . "First Name" . "\t" . "Last Name" . "\t";
$setData = '';
while ($rec = mysqli_fetch_row($setRec)) {
$rowData = '';
foreach ($rec as $value) {
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData) . "\n";
}
// convert to UTF-16 and add BOM
$setData = chr(255) . chr(254) . mb_convert_encoding($setData, "UTF-16LE", "UTF-8");
// add encoding in headers
header("Content-Encoding: UTF-16LE");
header("Content-type: text/csv; charset=UTF-16LE");
header("Content-Disposition: attachment; filename=User_Detail.xls");
header("Pragma: no-cache");
header("Expires: 0");
echo ucwords($columnHeader) . "\n" . $setData . "\n";
?>
Though you should really be using functions that will do escaping and such for you, like fputcsv() at a minimum.

Character encoding from MySQL to CSV using PHP

I am having problem with special character e.g. Russian characters are converted into ???? when I export MySQL query to CSV file.I used iconv() function but it is not working.
What should I do to fix this issue. I read different posts but nothing seems to be working for me
public function generateReport($nameReport,$db,$query,$host,$user,$pwd){
$con = mysql_connect($host,$user,$pwd);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db($db, $con);
if (!$db_selected)
{
die ("Can\'t use test_db : " . mysql_error());
}
$res = mysql_query($query);
if (!$res) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
$file='/home/'.$nameReport.'.csv';
$fp = fopen($file,'w') or exit("Unable to open file!");
if($fp){
$row = mysql_fetch_assoc($res);
$line = "";
$comma = "";
foreach($row as $name => $value) {
$line .= $comma . '"' . str_replace('"', '""', $name) . '"';
$comma = ",";
}
$line .= "\n";
fputs($fp, $line);
mysql_data_seek($res, 0);
while($row = mysql_fetch_assoc($res)) {
$line = "";
$comma = "";
foreach($row as $value) {
iconv( mb_detect_encoding( $value ), 'UTF-8', $value);
$line .= $comma . '"' . str_replace('"', '""', $value) . '"';
$comma = ",";
}
$line .= "\n";
fputs($fp, $line);
}
}
return '/home/'.$nameReport.'.csv';
}
Why not export directly from MySQL to CSV without going through PHP?
SELECT field_you_want, other_field_you_want
FROM your_table
INTO OUTFILE 'c:\\filename.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';
for russian only, you can try this
$value = mb_convert_encoding($value, 'KOI8-R','UTF-8' );
$line .= $comma . '"' . str_replace('"', '""', $value) . '"';
$comma = ",";
for other charsets, you have to find a way to get the charset info.
maybe, mb_detect_encoding with mb_detect_order
or maybe if you get that text from a website: from server header or charset defined at the head of page...

Exporting sql data to excel using PHP

I am trying to export data from my MySQL database to an excel file. Here is my code -
function cleanData(&$str) {
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
//File to export
$filename = "export_data_" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
$result = mysqli_query($dbc, $query) or die('Query failed!');
while(false != ($row = mysqli_fetch_assoc($result))) {
if(!$flag) {
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
array_walk($row, 'cleanData');
echo implode("\t", array_values($row)) . "\r\n";
}
exit;
mysqli_close($dbc);
The data comes fine but the header is one row right shifted. The rest of the data starts from the 1st column. How can i fix it?

Using Session variable for loop in php (3php script) with form checkbox for Excel sheet

<?php
session_start();
// $filename = "Report_" . date('MmDY') . ".xls";
// header("Content-type: application/octet-stream");
// header("Content-Disposition: attachment; filename=\"$filename\"");
// header("Pragma: no-cache");
// header("Expires: 0");
include ('../connection.php');
include ('../libchart/classes/libchart.php');
$calendarDate1 = $_SESSION['dateCalendarONE'];
$calendarDate2 = $_SESSION['dateCalendarTWO'];
$inputValue = $_SESSION['menuInputVALUE'];
$sql = ("
SELECT *
FROM `tally`, `category`
WHERE tally.catid = category.catid AND
date BETWEEN '" . $calendarDate1 . "' AND '" . $calendarDate2 . "'
AND CATLABEL='" . $inputValue . "'
GROUP BY `catlabel`
");
$rec = mysql_query($sql) or die (mysql_error());
$num_fields = mysql_num_fields($rec);
//loop count
for($i = 0; $i < $num_fields; $i++ )
{
$header .= mysql_field_name($rec,$i)."\t";
}
//Oraganize information on the database.
while($row = mysql_fetch_assoc($rec))
{
$line = '';
foreach($row as $brotocol)
{
if((!isset($brotocol)) || ($brotocol == ""))
{
$brotocol = "\t";
}
else
{
$brotocol = str_replace( '"' , '""' , $brotocol );
$brotocol = '"' . $brotocol . '"' . "\t";
}
$line .= $brotocol;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace("\r" , "" , $data);
if ($data == "")
{
$data = "\n BROTOCOL_ERROR: contact support!!!\n";
}
print "$header\n$data";
?>
When the session variable is passed, the exporting for excel is not looping through the and only reading 1 row. but When the sql statement is hard-coded in, it loops through as many rows as needed. Is the error with the loop alogrithm? or do I have to add another while loop in the code?

Categories