Blank spaces in CSV file - php

I am using php to export data from Database.My problem is.Data export successfully but it create two blank rows at beginning.I want to remove them.Here is my code
if($_POST){
$output = "";
$table = "schedule"; // Enter Your Table Name
$sql = mysql_query("select * from $table WHERE post_id='".$_POST['schedule_id']."'");
$columns_total = mysql_num_fields($sql);
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$output .= '"'.$heading.'",';
}
$output .="\n";
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.trim($row["$i"]).'",';
}
$output .="\n";
}
$filename = "schedule.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $output;
exit;
}

You should wrap string with spaces with double quotes or any other character.
See the function provided by this answer https://stackoverflow.com/a/3933816/1163444

Related

Excel import from mysql table

<?php
require_once("db_connect.php");
$arr = $_GET['arr'];
$selected_header = implode(', ', (array)$arr);
$sql = "SELECT $selected_header FROM release_ ORDER BY id DESC";
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename=CNC-'.date('Ymd').'.xls');
header('Pragma: no-cache');
header('Expires: 0');
$output = '';
$output .= '<table><tr>';
$header_arr = explode(',', $arr);
$len = count($header_arr);
for($a=0; $a<$len; $a++){
$output .= "<th style='width: 100px; text-align: center;'>" . $header_arr[$a] . "</th>";
}
$output .= '</tr>';
$res = mysqli_query($conn, $sql);
/*====this ruins everything=====*/
while($row = $res->fetch_assoc()){
$output = '<tr align="center">';
for($a=0; $a<$len; $a++){
$output .= "<td>" . $header_arr[$a] . "</td>";
}
echo "</tr>\t\n";
}
/*===============================*/
$output .= '</table>';
echo $output;
?>
I am able to get and display the header in the excel file but the content is not displaying at all. I get the whole string of row tag displayed. How am I able to display the data from the database to excel file. Please help.
I have done in my project(Cakephp) you can use like this own way :-
public function ExportToExcel(){
$users_id = $this->Session->read('selected_user_id');
$this->loadModel('User');
$conditions= array('User.usertype !='=>1);
if(!empty($users_id)){
$ids=explode(",",$users_id);
$conditions = array(
'User.id'=>$ids
);
}
$users = $this->User->find('all',array(
'conditions'=>$conditions,
'order'=>array('User.id Desc')
)
);
ini_set('max_execution_time', 600); //increase max_execution_time to 10 min if data set is very large
$filename = "Users" . date("Y.m.d") . ".xls";
header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename="' . $filename . '"');
$i = 1;
$row="";
$row_header="S.No."."\t"."Name "."\t"."Email"."\t"."Mobile"."\t"."Address"."\t"."Status"."\n";
if(!empty($users)){
foreach($users as $user){
if($user['User']['status']==1){
$status = "Active";
}
else{
$status = "Inactive";
}
$row .= $i++."\t".$user['User']['firstname'].' '.$user['User']['lastname']
."\t".$user['User']['email']
."\t".$user['User']['phone_number']
."\t".$user['User']['address']
."\t".$status
."\n";
}
}
$this->Session->delete('selected_user_id');
echo($row_header);
echo($row);
die;
}

Exporting data into Excel file using PHP

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

Export sql server Query Result in Excel file

I have code to export mysql query result data into Excel. But Now I use SQL Server.I haven't idea to fetch number of fields name. I find many blogs but they all are display php function of mysql database. I need php function which usefull to get field name and number from SQL Query Result
$header = '';
$result = '';
$exportData = sqlsrv_query($gaSql['link'], $sQuery) or die("$sQuery: " . sqlsrv_errors());
$fields = mysql_num_fields($exportData);
for ($i = 0; $i < $fields; $i++) {
if (in_array(mysql_field_name($exportData, $i), $_POST['optFieldName'])) {
$header .= mysql_field_name($exportData, $i) . "\t";
}
// $header .= mysql_field_name($exportData, $i) . "\t";
}
//
$row = array();
for ($i = 0; $i < mysql_num_rows($exportData); $i++) {
$result_excel = mysql_fetch_array($exportData);
array_push($row, $result_excel);
}
foreach ($row as $rowvalue) {
$line = '';
for ($j = 0; $j < count($_POST['optFieldName']); $j++) {
$value = $rowvalue[$_POST['optFieldName'][$j]];
if ((!isset($value) ) || ( $value == "" )) {
$value = "\t";
} else {
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$result .= trim($line) . "\n";
}
$result = str_replace("\r", "", $result);
if ($result == "") {
$result = "\nNo Record(s) Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=export.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$result";

php excel reader - ignore cells with special symbols

I use the parser for converting xls to csv http://code.google.com/p/php-excel-reader/
<?php
set_time_limit(300);
require_once 'excel_reader2.php';
$data = new Spreadsheet_Excel_Reader("file.xls", false, 'UTF-8');
$f = fopen('file.csv', 'w');
for($row = 1; $row <= $data->rowcount(); $row++)
{
$out = '';
for($col = 1; $col <= $data->colcount(); $col++)
{
$val = $data->val($row,$col);
// escape " and \ characters inside the cell
$escaped = preg_replace(array('#”#u', '#\\\\#u', '#[”"]#u'), array('"', '\\\\\\\\', '\"'), $val);
if(empty($val))
$out .= ',';
else
$out .= '"' . $escaped . '",';
}
// remove last comma (,)
fwrite($f, substr($out, 0, -1));
fwrite($f, "\n");
}
fclose($f);
?>
From some strange reason it skip cells with specials symbols - like ° or ®. How it can be fixed?
utf8_decode and html_entity_decode works for me:
<?php
set_time_limit(300);
require_once 'excel_reader2.php';
$data = new Spreadsheet_Excel_Reader("file.xls", false, 'UTF-8');
$f = fopen('file.csv', 'w');
for($row = 1; $row <= $data->rowcount(); $row++)
{
$out = '';
for($col = 1; $col <= $data->colcount(); $col++)
{
$val = $data->val($row,$col);
// escape " and \ characters inside the cell
$escaped = preg_replace(array('#”#u', '#\\\\#u', '#[”"]#u'), array('"', '\\\\\\\\', '\"'), $val);
$escaped = utf8_decode($escaped);
//$escaped = html_entity_decode($escaped);
if(empty($val))
$out .= ',';
else
$out .= '"' . $escaped . '",';
}
// remove last comma (,)
fwrite($f, substr($out, 0, -1));
fwrite($f, "\n");
}
fclose($f);
?>
Output:
"1","2","3","4","5"
"a","b","c","d","e"
"6","7","°","9","10"
"q","w","e","r","t"
"®","12","13","14","15"
"z","x","c","v","b"

all csv export data is in one column

I have code of csv export,which is using by me but the problem is all data is exporting on csv in one column.but i need data must be column separated,
<?php
$results= array(0=>array(name => "anil",agency=>"",phone=>"234235",cname=>"Atleta"),1=>array(name => "anil",agency=>"",phone=>"234235",cname=>"Atleta"));
$column = array("name","cname","agency","phone");
$writecolumn = array("Nome do Artista","Categoria","Agencia","Telefone");
$csv_export='';
for($i = 0; $i < count($column); $i++)
{
$csv_export.= $writecolumn[$i]."\t" ;
}
$csv_export.= "\n";
for($j = 0; $j < count($results); $j++)
{
for($i = 0; $i < count($column); $i++)
{
$csv_export.= $results[$j][$column[$i]]."\t";
}
$csv_export.= "\n";
}
$categoryname=$results[0]['cname'];
$filename = $categoryname."-Category-Artist-Data.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $csv_export;
exit;
?>
.
Use array_reduce, which reduces array to a single value, by applying function to each element, with initial value passed as third parameter, something like that:
$result= array(0=>array(name => "anil",agency=>"",phone=>"234235",cname=>"Atleta"),1=>array(name => "name_anil",agency=>"agency2",phone=>"234235",cname=>"Atleta_2"));
$csv_export = array_reduce($result, function($acc,$row) {
foreach($row as $key => $value) {
$acc .= $value;
$acc .= "\t";
}
$acc .= "\n";
return $acc;
},
"Nome do Artista\tCategoria\tAgencia\tTelefone\n")
$categoryname=$results[0]['cname'];
$filename = $categoryname."-Category-Artist-Data.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $csv_export;
exit;
Your code has delimiter (value separator) is 'tab' ('\t'). May be your CSV reading software need some configuration to start using 'tab' ('\t') as delimiter. I updated your code below and use ',' as delimiter. Microsoft Excel use ',' as default delimiter. Please try code below,
<?php
$results= array(0=>array('name' => "anil",'agency'=>"",'phone' =>"234235",'cname'=>"Atleta"),1=>array('name' => "anil",'agency'=>"",'phone'=>"234235",'cname'=>"Atleta"));
$column = array("name","cname","agency","phone");
$writecolumn = array("Nome do Artista","Categoria","Agencia","Telefone");
$csv_export='';
for($i = 0; $i < count($column); $i++)
{
$csv_export.= $writecolumn[$i]."," ;
}
$csv_export.= "\r\n";
for($j = 0; $j < count($results); $j++)
{
for($i = 0; $i < count($column); $i++)
{
$csv_export.= $results[$j][$column[$i]].",";
}
$csv_export.= "\r\n";
}
$categoryname=$results[0]['cname'];
$filename = $categoryname."-Category-Artist-Data.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $csv_export;
exit;
?>

Categories