Csv truncate 0 when generate php - php

I have the following code :
header('Content-Encoding: UTF-8');
header("Content-Type:application/csv;charset=UTF-8");
header('Content-Disposition: attachement; filename="' . $sFileName . '";');
header("Pragma: no-cache");
header("Expires: 0");
header("Refresh:0");
echo "\xEF\xBB\xBF";
$output = fopen('php://output', 'w');
fwrite($output, "sep=;\n");
fputcsv($output, array('1','2','3'), ";");
foreach ($aExport as $value) {
fputcsv($output, $value, ";");
}
fpassthru($output);
fclose($output);
exit;
For example if I have multiples 0000 witch need to be put in the first column it truncate the rest and it put only one zero. I dont'n understand why. Can you help me please ? Thx in advance

Related

Forcing PHP to download file via browser

I'm currently trying to make a file download in the user's browser but have so far been unable to make it happen.
I've looked at other answers on stackoverflow.com and so far haven't found anything that has solved my problem.
My process is as follows:
I create the filename and filepath, then set headers:
$date = new DateTime();
$currentDateTime = $date->format("Y-m-d H:i:s");
$filename = "{$name}_{$currentDateTime}.csv";
$filepath = $rootfull . "/{$filename}";
// Set headers
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="' . $filepath . '"');
header('Content-Length: ' . filesize($filepath));
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Transfer-Encoding: binary");
header('Pragma: no-cache');
I then create the file and start writing to it:
// Write header
fputcsv($output, $header);
fputcsv($output, array()); // Empty line
// Write column names
$column_headers = array_keys(array_flip($columns));
foreach ($data as $row)
{
fputcsv($output, $row);
}
echo readfile($filepath);
die();
The file gets generated and written to the specified location (in this case /var/www/<project>/<filename>.csv without any indication to the user that anything has happened. No download dialog, nothing.
If anyone can spot a problem with my code or my process, please point it out and preferably suggest a better/alternative way of doing it, any help at all is welcome at this point.
If no benefit (poor mans cache) to writing to disk then maybe something like this writing to buffer:
<?php
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="dump_' . date('Ymd') . '.csv"');
header("Pragma: no-cache");
header("Expires: 0");
$this->outputCSV($results);
exit(); //->
public function outputCSV($data, $useKeysForHeaderRow = true)
{
if ($useKeysForHeaderRow) {
array_unshift($data, array_keys(reset($data)));
}
$outputBuffer = fopen("php://output", 'w');
foreach($data as $v) {
fputcsv($outputBuffer, $v);
}
fclose($outputBuffer);
}
?>

Outputting and saving a csv in PHP

I am currently creating and outputting a CSV as follows:
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=file.csv');
header("Cache-Control: no-store, no-cache");
$df = fopen('php://output', 'w');
fprintf($df, chr(0xEF).chr(0xBB).chr(0xBF));
foreach ($csvLines as $csvLine) {
fputcsv($df, $csvLine);
}
exit;
However, I would like to not only output but also save this file to disk. How can I write $df to a file?
Note Suggestions on improving my generating the CSV are welcome :)
The simplest answer is to write to the file instead of php://output, and then send that file directly to the browser using readfile()
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=file.csv');
header("Cache-Control: no-store, no-cache");
$df = fopen('/path/to/where/you/want/the/file/on/disk.csv', 'w');
fprintf($df, chr(0xEF).chr(0xBB).chr(0xBF));
foreach ($csvLines as $csvLine) {
fputcsv($df, $csvLine);
}
readfile('/path/to/where/you/want/the/file/on/disk.csv');
exit;
Simply write to two file pointers:
$out = fopen('php://output', 'w');
$file = fopen('somefile.csv');
fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));
fprintf($file, chr(0xEF).chr(0xBB).chr(0xBF));
foreach ($csvLines as $csvLine) {
fputcsv($out, $csvLine);
fputcsv($file, $csvLine);
}
exit;

Read and write using fgetcsv and fputcsv

I have a 3rd party source from where I am getting "csv" file. I wrote it inside a quote because it says it's a csv file but basically it's not.
So I am taking that main source file then reading and putting the data in a "PROPER" csv file.
The read and write is fine but the problem is when it saves the properly quoted data is writing on the script file itself.For example if the my php file name is "fixcsv.php" then I am getting the downloadable file as "fixcsv.php".
My code
$headings = array('HID');
$handle = fopen("MonC1.csv", "r");
$data = fgetcsv($handle, 0, ";",'"');
$fh = fopen('php://output', 'w');
ob_start();
fputcsv($fh, $headings);
// Loop over the * to export
if (! empty($data)) {
foreach ($data as $item) {
// echo $item;
fputcsv($fh, array($item));
}
}
$string = ob_get_clean();
$filename = 'csv_' . date('Ymd') .'_' . date('His');
// Output CSV-specific headers
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.csv\";" );
header("Content-Transfer-Encoding: binary");
exit($string);
Any help is highly appreciated. Thanks in advance.
Your Content-Disposition has a semi-colon in the wrong place (per the spec). Should be:
header("Content-Disposition: attachment; filename=\"$filename.csv\" );

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

transfer data from Mysql to excel

I had created a website using php. In that website,I want to create a report like thing,which involves transferring details from one table to an excel sheet which is downloadable.Is there any way to do this work? Please help me to find the solution.
Thank you.
You can fetch all rows from the database and use fputcsv function to put it as csv
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename=export.csv");
header("Content-Transfer-Encoding: binary");
$csvHandler = fopen("php://output", 'w');
while ($row = mysql_fetch_array ($res))
{
fputcsv($csvHandler, $row);
}
You can use PHPExcel for generating data
and a simple function for file download:
function show_download($data, $name, $type = "unknown/unknown") {
header('Content-Type: ' . $type);
header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Content-Disposition: attachment; filename="' . $name . '"');
header('Content-Length: ' . strlen($data));
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
print $data;
exit();
}
You can create a script that exports a CSV file like this :
header('Content-type: text/csv');
header("Content-Disposition: attachment; filename=clients_" . date("Ymd") . ".csv");
//Open PHP output stream
$fd = fopen('php://output', 'w');
$tab = array();
//get your results from your database
foreach ($results as $res)
$tab[] = array($res->Client_Name, $res->Client_Email);
foreach ($tab as $val)
fputcsv($fd, $val);
fclose($fd);

Categories