Come rendere fputcsv “echo” i dati
-
11-10-2019 - |
Domanda
Ho bisogno di un modo per rendere le fputscv
dati funzione di scrittura per la del browser on-the-fly, invece di creare un file temporaneo, il salvataggio dei dati in quel file e facendo un echo file_get_contents()
.
Soluzione
Ho trovato questo sul sito web documenti PHP, primo commento sotto il riferimento alla funzione:
function outputCSV($data) {
$outstream = fopen("php://output", 'w');
function __outputCSV(&$vals, $key, $filehandler) {
fputcsv($filehandler, $vals, ';', '"');
}
array_walk($data, '__outputCSV', $outstream);
fclose($outstream);
}
E una seconda opzione:
$csv = fopen('php://temp/maxmemory:'. (5*1024*1024), 'r+');
fputcsv($csv, array('blah','blah'));
rewind($csv);
// put it all in a variable
$output = stream_get_contents($csv);
Spero che questo aiuti!
A proposito i documenti PHP dovrebbe sempre essere la vostra prima fermata quando si cerca di capire le cose. : -)
Altri suggerimenti
<?php
$out = fopen('php://output', 'w');
fputcsv($out, array('this','is some', 'csv "stuff", you know.'));
fclose($out);
?>
Per quanto il richiedente originale ha voluto "scrivere al browser al volo", forse vale la pena notare (come era il mio caso e nessuno ne ha parlato) che, se si vuole forzare un nome di file e una finestra che chiede di scaricare un file nel browser, è necessario impostare le intestazioni appropriate prima di emettere qualsiasi cosa con fputcsv
:
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=myFile.csv');
La produzione di un CSV in realtà non è poi così difficile (l'analisi di un CSV è un po 'più coinvolti).
Codice di esempio per la scrittura di una matrice 2D in formato CSV:
$array = [
[1,2,3],
[4,5,6],
[7,8,9]
];
// If this CSV is a HTTP response you will need to set the right content type
header("Content-Type: text/csv");
// If you need to force download or set a filename (you can also do this with
// the download attribute in HTML5 instead)
header('Content-Disposition: attachment; filename="example.csv"')
// Column heading row, if required.
echo "Column heading 1,Column heading 2,Column heading 3\n";
foreach ($array as $row) {
$row = array_map(function($cell) {
// Cells containing a quote, a comma or a new line will need to be
// contained in double quotes.
if (preg_match('/["\n,]/', $cell)) {
// double quotes within cells need to be escaped.
return '"' . preg_replace('/"/', '""', $cell) . '"';
}
return $cell;
}, $row);
echo implode(',', $row) . "\n";
}