all csv export data is in one column - php

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

Related

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"

Blank spaces in CSV file

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

How can i export mysql table to csv file and download it

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();

Categories