I have a page that allow user to export particular data in .xls file.
Here is the code.
if(isset($_SESSION['name'])){
$user_name=$_SESSION['name'];$sql = "select * from asset_details inner join bank_details on asset_details.user_id=bank_details.user_id inner join merchant_details on asset_details.user_id=merchant_details.user_id inner join merchant_status on asset_details.user_id=merchant_status.user_id inner join merchant_ids on asset_details.user_id=merchant_ids.user_id inner join terminal_details on asset_details.user_id=terminal_details.user_id where asset_details.user_id='$user_name' order by merchant_details.time_date asc" ; $result = mysqli_query($db,$sql); function filterData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// file name for download
$fileName = "report" . date('Ymd') . ".xls";
// headers for download
header("Content-Disposition: attachment; filename=\"$fileName\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
foreach($result as $row) {
if(!$flag) {
// display column names as first row
echo implode("\t", array_keys($row)) . "\n";
$flag = true;
}
// filter data
array_walk($row, 'filterData');
echo implode("\t", array_values($row)) . "\n";
}
exit;}
The Problem is that while exporting the data it takes column name from database rather than from the column name on the page.
Related
My problem looks like this at the front side:
After choosing which of my users I want to export:
I'm sending AJAX request containing their database ids to external file named exportUsers.php.
So this is how back end of my problem looks like:
When data arrive to exportUsers.php, I query the database and make array($data) like this, which I want to export into Excel file.
This is how i tried to trigger download:
function cleanData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
$flag = false;
foreach($data as $row1) {
if(!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row1)) . "\r\n";
$flag = true;
}
array_walk($row, __NAMESPACE__ . '\cleanData');
echo implode("\t", array_values($row1)) . "\r\n";
}
$filename = "users_data" . date('Ymd') . ".xls";
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=\"$filename\"");
But this is all I see in Network tool of my browser:
But no download was triggered. Please help
Try this
session_start();
include "connection.php";
$sql= mysql_query("select * from table") or die(print "Failed Download :".mysql_error());
$columns_total = mysql_num_fields($sql);
// Get The Field Name
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$output .= '"'.$heading.'",';
}
$output .="\n";
// Get Records from the table
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}
// Download the file
$filename = "FileName.xls";
header('Content-type: application/xls');
header('Content-Disposition: attachment; filename='.$filename);
echo $output;
//jzend...
exit;
?>
I need to display the complete address details in Address column, but I am displayed like this:
.
Can you please help me? How to solved the issue.
<?php $users = elgg_get_entities(array( 'type' => 'user', 'limit' => 9999)); $data = array(); foreach($users as $euser){
if($euser->banned == "no" && $euser->enabled == "yes") {
if(!$euser->ext_mod){
$user = new SsportalUser($euser);
$row = array();
$row['Address'] = $user->basic('address');
array_push($data, $row);
} } }function cleanData(&$str) {
$str = preg_replace('/^\s+|\s+$|\s+(?=\s)/', '', $str);
$str = preg_replace('/\s/u', '', $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"'; } header("Content-Disposition: attachment;filename=active_users_list.xls");header("Content-Type: application/vnd.ms-excel"); $flag = false;foreach($data as $row) {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;
I am using WP_List_Table class to make a table at back end which fetches records from myCustomTable. Is there any feature/plugin available to export the single & multiple rows to CSV format. I have tried so many plugin but they all come up with the whole table export.
Thanks
yes you can do. this an an example of my code where i use to get the DB table to excel formate. you just replace the DB connection, table,table fields, and query as required this code may helps you
<?php
include '../common/inc.common.php';//db connectivity
$class=$_REQUEST['class_id'];//get the class id
$line .= "\n";
$filename='../app/class_export_student_hsc.csv';// file name
$fp = fopen($filename, "w");
$sql="SELECT t1 . * ,y.aca_year
FROM (
SELECT name,fathername,school_name,edu_disctrict,revenue_disctrict,nationality,religion,caste,castetype,gender,dob,dobword,mark1,stat
FROM **myCustomTable**
)t1, academic_years y
WHERE t1.academic_year=y.refid
AND t1.class =$class
";
$studentArray=$Cobj->run_query($sql);
$line = "";
foreach($studentArray as $name => $valuee) {
$comma = "";
foreach($valuee as $key2 => $value){
$line .= $comma . '"' . str_replace('"', '""', $key2) . '"';
$comma = ",";
}
$line .= "\n";
break;
}
foreach($studentArray as $name => $valuee) {
$comma = "";
foreach($valuee as $key2 => $value){
$line .= $comma . '"' . str_replace('"', '""', $value) . '"';
$comma = ",";
}
$line .= "\n";
}
fputs($fp, $line);
fclose($fp);
if (file_exists($filename)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
readfile($filename);
exit;
}
?>
I have a program that turns a file into an excel file but for some reason my phone and email fields get switched. It looks like this -
firstname lastname email phone
test bi#gmail.com
test d 813-767 leighmimail.com
test Pds 888-413 Bperotects.com
the email and phone should be switched
Code:
<?php
session_start();
$num = $_SESSION['num'];
$firstname = $_SESSION['firstnameexport'];
$lastname = $_SESSION['lastnameexport'];
$email = $_SESSION['emailexport'];
$phone = $_SESSION['phoneexport'];
for($i =0; $i< $num; $i++){
$data[$i] = array(
"firstname" => $firstname[$i] , "lastname" => $lastname[$i], "email" => $email[$i], "phone" => $phone[$i]);
}
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;
foreach($data as $row) {
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";
}
unset($_SESSION['num'],$_SESSION['firstnameexport'],$_SESSION['lastnameexport'],$_SESSION['emailexport'],$_SESSION['phoneexport']);
?>
Thank you for your time!
Fixed it - all I had to do was switch some of the session variables out so it would give the correct value for the right column.
Thank you for your time!
Am tryng to export data to csv file from mysql. I took the following script but the $result variable have error : mysql_num_fields tells the argument supplied is not valid
$filename = 'myfile.csv';
$result = db_query("SELECT * FROM {loreal_salons}");
drupal_set_header('Content-Type: text/csv');
drupal_set_header('Content-Disposition: attachment; filename=' . $filename);
$count = mysql_num_fields($result);
for ($i = 0; $i < $count; $i++) {
$header[] = mysql_field_name($result, $i);
}
print implode(',', $header) . "\r\n";
while ($row = db_fetch_array($result)) {
foreach ($row as $value) {
$values[] = '"' . str_replace('"', '""', decode_entities(strip_tags($value))) . '"';
}
print implode(',', $values) . "\r\n";
unset($values);
}
If you don't mind using a temporary file, you can do:
SELECT *
INTO OUTFILE '/tmp/myfile.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM loreal_salons
as your query, then simply do:
header('Content-type: text/csv');
header('Content-disposition: attachment; filename=myfile.csv');
readfile('/tmp/myfile.csv');
unlink('/tmp/myfile.csv');
exit();