Why my CSV file was start filling from the 2nd line? - php

I am exporting MySQL data successfully to a csv file. But in the csv file first line was empty and data starts from 2nd line. Below is my code.
$delimiter = ";";
$generated_date = date("Y-m-d-H-i-s");
$filename = 'order_detail_report'.$generated_date.".csv";
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '";');
$output = fopen('php://output', 'w+');
fputcsv($output, array('Order Type','Order Number','EAN','Article #'),$delimiter);
sql query
<?php
$lineData = array();
$query = "my select query";
$res = mysqli_query($mysqliConn,$query);
while($result= mysqli_fetch_assoc($res))
{
$lineData[] = $result;
fputcsv($output, $lineData, $delimiter);
unset($lineData);
}
Data was exporting successfully to csv but it was starting from 2nd line, any help would be greatly appreciated.
EDIT
<?php
//header info for browser
$delimiter = ";";
$generated_date = date("Y-m-d-H-i-s");
$filename = 'order_detail_report'.$generated_date.".csv";
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '";');
$output = fopen('php://output', 'w');
fputcsv($output, array('Order Type','Order Number','EAN','Article #','Title','Amazon Price','ERP Price','Requested Quantity','Dispatch Quantity','Rejected Quantity','Cancelled Quantity','Delivery Date','Status','EDD','LDD','Dispatch Center','Order Received','Price Status','Country'),$delimiter);
?>
I just removed all my mysql related query and only using the above one.

Related

Wrap CSV values generated by PHP fputcsv() with “ ”

So, my code generates a CSV file using PHP's built-in fputcsv function
my code
$delimiter = ';';
$filename = "members_" . date('Y-m-d') . ".csv";
//create a file pointer
$f = fopen('php://memory', 'w');
//set column headers
$fields = array('"FK"','"ID"', '"Name"', '"Email"', '"Phone"', '"Created"');
fputcsv($f, $fields, $delimiter, ' ');
//move back to beginning of file
fseek($f, 0);
//set headers to download file rather than displayed
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
//output all remaining data on a file pointer
fpassthru($f);
// }
exit;
output :
FK;"ID";"Name";"Email";"Phone";"Created"
but i want like
"FK";"ID";"Name";"Email";"Phone";"Created"
please help me

Download multiple .txt files into .zip file with PHP

Now in system it is possible to download .txt file generated from MySQL table row. I am trying to make it possible to download all .txt files in one zip file. Actually, I stuck on the point where I am not sure if my approach is possible.
if (isset($_POST["ExportAll"])) {
$query = $con->query("SELECT id, filename FROM thistable");
$MultiArray = Array();
while($result = $query->fetch_assoc()){
$rowArray = Array();
$rowArray[] = $result['id'];
$rowArray[] = $result['filename'];
$MultiArray[] = $rowArray;
}
foreach ($MultiArray as $arg) {
$query = "SELECT * FROM thistable WHERE id LIKE '" . $arg[0] . "';";
$result = mysqli_query($con, $query);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $arg[1] );
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
$output = fopen("php://output", "w");
while ($row = mysqli_fetch_assoc($result)) {
foreach(array_slice($row,2) as $line) {
echo ("$line \r\n");
}
}
fclose($output);
}
}
It is possible to put all $output values into some kind of $zipArray = Array() and then download it with header("Content-type: application/zip");
?
Yes you can download multiple text files as single zip file using php ZipArchive class. This is sample only you can try with your own scenario.
$zipname = 'sample.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
$files_array = ["sample1", "sample2"]; // List of file names
foreach ($files_array as $file) {
$row = ["Line 1", "Line 2", "Line 3", "Line 5"]; // Assuming as your table row
$filename = $file.".txt";
$lines_to_add = "";
foreach(array_slice($row, 2) as $line) {
$lines_to_add .= $line."\r\n";
}
$zip->addFromString($filename, $lines_to_add); // Adding lines to file
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
unlink($zipname); // Remove zip file if you don't want be in server

Trying to automatically open a dynamically generated CSV file from PHP script?

I'm successfully getting the desired output in console, but the browser isn't automatically downloading the CSV file.
header('Content-Type: application/csv');
$filename = 'Totals Report for ' . $name . ' All-Time.csv';
header('Content-Disposition: attachment; filename="'.$filename.'";');
$output = fopen('php://output', 'rb');
// output the column headings
fputcsv($output, array('Procedure Name', 'Totals'));
foreach ($rows as $row){
fputcsv($output, $row);
}
fopen($filename);
fclose($output);
A sample wich running in my browser:
$csv= '"Procedure Name", Totals'."\n";
$rows= array(
array('aaa', 'bbb'),
array('123', '456')
);
foreach ($rows as $row){
$csv .= implode(",",$row)."\n";
}
$filename= 'Totals Report for '.$name.' All-Time.csv';
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="'.$filename.'";');
die($csv);
Bah, this got unruly in the comments. I took it a step further and made it loop through the values too!
// Set headers
header('Content-Type: text/csv');
$filename = 'Totals Report for ' . $name . ' All-Time.csv';
header('Content-Disposition: attachment; filename="'.$filename.'";');
// Column titles
echo 'Procedure Name,Totals' . "\n"; // Don't forget the newlines!
// Data
foreach ($rows as $row) {
foreach ($row as $index => $value) {
echo $value;
if ($index < count($row) - 1) {
echo ',';
}
}
echo "\n";
}
You could also buffer it into a file so you can use fputcsv. That would work almost exactly as your current code, but at the end you'd have echo file_get_contents($the_buffer_file);
The main point is that all you need to do is output your data in CSV format, i.e. separate values by commas and a new line is a new row. It would also be smart to escape the values with quotation marks (not shown in my code).

Encoding characters when exporting using php in csv format

I have a problem with my export.
So I tried to export data to .csv with the following code :
$output = fopen('php://output', 'w');
$sFileName = 'test.csv';
header('Content-Disposition: attachement; filename="' . $sFileName . '";');
header("Content-Type:application/csv;charset=UTF-8");
fwrite($output, "sep=;\n");
fputcsv($output, array('Nom', 'Prenom'), ";");
foreach ($aFilterGifts as $value) {
fputcsv($output, $value, ";");
}
fpassthru($output);
fclose($output);
exit;
Where the $aFilterGifts is an array with data. But If I have in Nom, data like this Fossé, when I export I get FossГ©.
Is there a solution? Thank you in advance.
I found the error, it's necessairy to make $output = fopen('php://output', 'w'); after all headers,so thhe code is like this :
$sFileName = 'test.csv';
header('Content-Disposition: attachement; filename="' . $sFileName . '";');
header("Content-Type:application/csv;charset=UTF-8");
$output = fopen('php://output', 'w');

Non-ascii characters in fputcsv

So I have a simple script that writes some data to a CSV-file. The file contains a few non-ascii characters (norwegian characters) which are not displayed correctly in when opened in Excel. However they are displayed correctly in OpenOffice. Does anyone know how to fix this?
$fp = fopen('php://output', 'w');
if(!$fp)
{
echo "Could not write CSV-file"; die;
}
$filename = sprintf('%s_export_%s.csv', $marketplace, date('Y_m_d_H_i_s'));
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Pragma: no-cache');
header('Expires: 0');
foreach($collection as $i => $item)
{
$result = array();
$result[] = $item->getData('email');
$result[] = $item->getData('firstname');
$result[] = $item->getData('lastname');
fputcsv($fp,$result, ";");
}
flush();
fclose($fp);
Windows needs a BOM to know that a file is UTF-8 and open it correctly.
Before your foreach, add the following line:
fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));

Categories