I have written the following class to export database results to a CSV file.
<?php
class Export {
public static function tocsv($results = array(), $fields = array()) {
$schema_insert = '"'.implode('","', $fields).'"';
$out .= $schema_insert."\n";
foreach($results as $row) {
$schema_insert = '';
$schema_insert .= '"'.$row->week_ending.'",';
$schema_insert .= '"'.$row->project.'",';
$schema_insert .= '"'.$row->employee.'",';
$schema_insert .= '"'.$row->plots.'",';
$schema_insert .= '"'.$row->categories.'"';
$out .= $schema_insert."\n";
}
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Length: " . strlen($out));
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$filename");
echo $out;
exit;
}
}
?>
The output is:
"Week ending","Project name","Plot numbers","Categories","Employee"
"Friday 08 May 2015","Big Road","Tracey Smith","1A, 2A, 3A"," Water meter, 1st fix inc lagging"
However, when I open with Excel everything is in one column. Have I missed something?
Thanks.
Use a semicolon as your fieldterminator instead of a comma, it's an Excel thing really, not a php thing.
Related
I am trying to write data from database to a downloadable excel sheet. The code is working in the sense that it downloads the file with the desired name. However if I open the Excel sheet the cells are empty and my data is not in the sheet.
Here is my code
require_once('include/connect_pdo.php');
$myschool = $_POST['country'];
$findschool = $conn->prepare("SELECT Query");
$findschool->execute();
$filename = "Name";
$file_ending = "xls";
//header info for browser
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename= $filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
/*******Start of Formatting for Excel*******/
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
//start of printing column names as names of MySQL fields
for ($i = 0; $i < mysql_num_fields($result); $i++) {
echo mysql_field_name($result,$i) . "\t";
}
print("\n");
//end of printing column names
//start while loop to get data
while($row = mysql_fetch_row($result))
{
$schema_insert = "";
for($j = 0; $j < mysql_num_fields($result); $j++)
{
if(!isset($row[$j]))
$schema_insert .= "NULL".$sep;
elseif ($row[$j] != "")
$schema_insert .= "$row[$j]".$sep;
else
$schema_insert .= "".$sep;
}
$schema_insert = str_replace($sep."$", "", $schema_insert);
$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
print(trim($schema_insert));
print "\n";
}
This sorted my problem.
Header('Content-Description: File Transfer');
Header('Content-Encoding: UTF-8');
Header('Content-type: text/csv; charset=UTF-8');
Header('Content-Disposition: attachment; filename=' . '$filename' . '.csv');
echo "\xEF\xBB\xBF"; // UTF-8 BOM
$output = fopen("php://output", "w");
fputcsv($output, array('Number1', 'Number 2'));
$findschool = $conn->prepare("SELECT Query Here);
$findschool->execute();
while ($result = $findschool->fetch(PDO::FETCH_ASSOC)) {
fputcsv($output, $result);
}
fclose($output);
XLS is Microsoft's proprietary binary format. What you create with your PHP code is a CSV file. Try changing your file extension to .csv and Content-Type header to text/csv.
Exporting excel file from php show error after download and open the file:
the file you are trying to open is in a different format .xls
I want to download table field and fill data and upload to database again using php code.
I tried many application type. I just want to give user a file with structure which contains database field name and user will add data and will again upload to database using php.
<?php
`session`_start();
include 'db.php';
/*******EDIT LINES 3-8*******/
$DB_TBLName = $_POST["tablename"]; //MySQL Table Name
$filename = $_POST["excelfilename"]; //File Name
/*******YOU DO NOT NEED TO EDIT ANYTHING BELOW THIS LINE*******/
//create MySQL connection
$sql = "SHOW COLUMNS FROM $DB_TBLName";
//execute query
$result = $conn->query($sql);
$file_ending = "xls";
//header info for browser
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$filename.xls");
header ('Content-Transfer-Encoding: binary');
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header ('Cache-Control: cache, must-revalidate');
header ('Pragma: public');
/*header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment; filename=$filename.xls");
header("Pragma: no-cache");
header("Expires: 0");*/
/*******Start of Formatting for Excel*******/
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
//start of printing column names as names of MySQL fields
while($row = $result->fetch_assoc())
{
echo $row['Field'] . "\t";
}
print("\n");
//end of printing column names
//start while loop to get data
while($row = $result->fetch_assoc())
{
$schema_insert = "";
for($j=0; $j<$result->field_count;$j++)
{
if(!isset($row[$j]))
$schema_insert .= "NULL".$sep;
elseif ($row[$j] != "")
$schema_insert .= "$row[$j]".$sep;
else
$schema_insert .= "".$sep;
}
$schema_insert = str_replace($sep."$", "", $schema_insert);
$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
print(trim($schema_insert));
print "\n";
}
?>
I have a php code that selects an query from a postgres db and creates a xls file and downloads the same. The code is as follows :
<?php
$xls_filename = 'filename.xls'; // Define Excel (.xls) file name
$Connect = pg_connect ("host=xxxx port=5432 dbname=xxxx user=xxx password=xxx");
$sql = 'SELECT * FROM "tablename"';
$result = pg_query($sql);
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$xls_filename");
header("Pragma: no-cache");
header("Expires: 0");
// Define separator (defines columns in excel & tabs in word)
$sep = "\t"; // tabbed character
// Start of printing column names as names of fields
for ($i = 0; $i<pg_num_fields($result); $i++) {
echo pg_field_name($result,$i) . "\t";
}
print("\n");
// End of printing column names
// Start while loop to get data
while($row = pg_fetch_row($result))
{
$schema_insert = "";
for($j=0; $j<pg_num_fields($result); $j++)
{
if(!isset($row[$j])) {
$schema_insert .= "".$sep;
}
elseif ($row[$j] != "") {
$schema_insert .= "$row[$j]".$sep;
}
else {
$schema_insert .= "".$sep;
}
}
$schema_insert = str_replace($sep."$", "", $schema_insert);
$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
print(trim($schema_insert));
print "\n";
}
}
?>
I want to zip this xls file which is created rather then just downloading it.
How do I create a xls file in the directory instead of downloading it.
The problem is your variable.when your file name has space you have to use quotes like below:
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename='$xls_filename'");
You can use below code that work fine
$fileNames = WWW_ROOT . 'uploads' . DS . 'export' . DS . 'DYNAMIC_FILE_NAME_'. $ANY_DYNAMIC_PART.'.xls';//Dynamic Path of the directory
if (file_exists($fileNames)) {
$file = $fileNames;
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment; filename=\"NEWFILENAME.xls\"");
header("Content-Transfer-Encoding: binary");
header("Pragma: no-cache");
header("Expires: 0");
readfile($fileNames);exit;
}
I am trying to create a CSV file that can be downloaded by the user and not have the data permanently saved on the server.
I am using mySQL and PHP for this page. I get the data in the right format to show up ("echo") on the webpage but not able to get the file to generate/download...maybe I am missing something or looking in the wrong place but any help would be great!
I have been trying several script both my own and others I have found but the one I currently have is below:
$file = 'export';
$colresult = mysql_query("SHOW COLUMNS FROM ".$tbl_name."");
if (mysql_num_rows($colresult) > 0) {
while ($row = mysql_fetch_assoc($colresult)){
$csv_output .= $row['Field'].", "; $i++; } } $csv_output .= "\n";
$csvresult = mysql_query($sql);
while ($rowr = mysql_fetch_row($csvresult)) {
for ($j=0;$j<$i;$j++) { $csv_output .= $rowr[$j].", ";
}
$csv_output .= "\n"; }
$filename = $file."_".date("Y-m-d_H-i",time()).".csv";
header("Content-type: application/csv");
header("Content-disposition: attachment;filename=".$filename.".csv");
readfile("../documents/csv/".$filename.".csv");
$fp = fopen($filename, 'w');
foreach($csvret as $csvret){
fputcsv($fp, $csvret);
}
print $csv_output;
print $filename;
Thanks!
You'll need to pass some headers to force the web browser to recognize the file as "downloadable":
<?php
header('Content-Description: File Transfer');
header("Content-Type: application/csv");
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
readfile($filename);
exit;
Simply add that code in place of:
print $csv_output;
print $filename;
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.