I am using php to create CSV files to be able to import this information into an other program. For some reason the created csv files is not imported in this program but when I open this file first in Excel and save it I am able to import into this other program.
Maybe an encoding problem? Suggestions how to solve this?
File export php
.
File save Excel
<?php
for ($j = 0; $j <= $aantal_regels; $j++)
{
$csv_output .= $klantnaam.';';
$csv_output .= $klant_ref.';';
$csv_output .= $posno[$j].';';
$csv_output .= $aantal[$j].';';
$csv_output .= $dikte[$j].';';
$csv_output .= $kwaliteit[$j].';';
$csv_output .= "\n";
}
$filename = $file;
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$lang['lijst_dxf']." ".$dossier_nr." ".$klantnaam." ".$klant_ref.".csv");
?>
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.
I want to export data of a sql table in csv. I am using the follwoing code :
<?php
if(isset($_POST['export']))
{
$file = 'email_csv'; // ?? not defined in original code
$results = $wpdb->get_results("SELECT * FROM `scholarship_uesr`;",ARRAY_A);
if (empty($results)) {
return;
}
$csv_output = '"'.implode('";"',array_keys($results[0])).'";'."\n";;
foreach ($results as $row) {
$csv_output .= '"'.implode('";"',$row).'";'."\n";
}
$csv_output .= "\n";
$dir = "/home/modifoun/public_html/wp-content/plugins/schloarship/menu-pages/csv/";
$filename = $file."_".date("Y-m-d_H-i",time()).".csv";
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
// echo "<div class='alert alert-info'>Data Written to CSV File. <a href='".$geturl."' download>Click Here to Download</a></div>";
}
$allsubs = "SELECT * FROM `scholarship_uesr`";
$select_query = $wpdb->get_results($allsubs);
//echo $wpdb->last_error;
?>
<form method="post" action="#" enctype="multipart/form-data">
<input type="submit" name="export" class='btn btn-danger' value="Export Data to CSV !!!">
</form>
When I am using to this code then it is directly print the data of database instead of downloading the file.
When i turn on the error_reporting then it is throwing error :
Warning: Cannot modify header information - headers already sent by (output started at /home/modifoun/public_html/wp-admin/includes/template.php:2041) in /home/modifoun/public_html/wp-content/plugins/schloarship/menu-pages/student_list.php on line 45
Warning: Cannot modify header information - headers already sent by (output started at /home/modifoun/public_html/wp-admin/includes/template.php:2041) in /home/modifoun/public_html/wp-content/plugins/schloarship/menu-pages/student_list.php on line 46
Warning: Cannot modify header information - headers already sent by (output started at /home/modifoun/public_html/wp-admin/includes/template.php:2041) in /home/modifoun/public_html/wp-content/plugins/schloarship/menu-pages/student_list.php on line 47
How can I export data to csv using wordpress
You need to run this before output has started. It looks like you have this in your template file?
Try adding this to your functions.php file.
add_action('init', 'exportCsv');
function exportCsv() {
if(isset($_POST['export']))
{
$file = 'email_csv'; // ?? not defined in original code
$results = $wpdb->get_results("SELECT * FROM `scholarship_uesr`;",ARRAY_A);
if (empty($results)) {
return;
}
$csv_output = '"'.implode('";"',array_keys($results[0])).'";'."\n";;
foreach ($results as $row) {
$csv_output .= '"'.implode('";"',$row).'";'."\n";
}
$csv_output .= "\n";
$dir = "/home/modifoun/public_html/wp-content/plugins/schloarship/menu-pages/csv/";
$filename = $file."_".date("Y-m-d_H-i",time()).".csv";
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
// echo "<div class='alert alert-info'>Data Written to CSV File. <a href='".$geturl."' download>Click Here to Download</a></div>";
}
}
The only thing is required is ob_start() and ob_end_clean()
Just after if(isset($_POST['export'])) use ob_start() and just before the closing braces of this if statement use ob_end_clean().
use below headers
header('Content-Description: File Transfer');
header("Content-Type: application/csv") ;
header("Content-Disposition: attachment; filename=Report.csv");
header("Pragma: no-cache");
header("Expires: 0");
I am want to export data to excel sheet from custom table.this table is created from wp_list_table in admin section of wordpress. followed is the code i implemented to fetch the data in excel sheet.
global $wpdb;
$data ="";
$values = $wpdb->get_results('SELECT company_name,firstname,email,phone,country FROM (table_name) where id='.$id.' ;',ARRAY_A);
$header = "Name" . "\t";
$header .= "Email" . "\t";
$header .= "Phone" . "\t";
$header .= "Country" . "\t";
foreach($values as $line){
$row1 = array();
$row1[] = $line['firstname'];
$row1[] = $line['email'];
$row1[] = $line['phone'];
$row1[] = $line['country'];
$data .= join("\t", $row1)."\n";
}
header("Content-type: application/xls");
header("Content-Disposition: attachment; filename=expot.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
exit();
My issue is that on exporting the data whole html of the page is also there in my excel sheet. my excel sheet look like attached image
Please suggest whats wrong in the code. why it is getting whole page html in excel sheet.
Regards
swati
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.
I am working on export excel data to using php
but it has problem on downloaded as csv with comma separated values
but i need XLS file with table field values
I using the below code
$values = mysql_query("SELECT * FROM $table");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i-1;$j++) {
$csv_output .= $rowr[$j]."; ";
}
$csv_output .= "\n";
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
$rown=0;
while( $row = mysql_fetch_assoc($values)){
if($rown++==0)
$csv_output.=implode(";",array_keys($row)."\n";
$csv_output.=implode(";",array_values($row)."\n";
}