Frage

brauche ich einen Weg, um die fputscv Funktion Schreibdaten an das zu machen Browser on-the-fly stattdessen eine temporäre Datei zu erstellen, Speichern von Daten in diese Datei und eine echo file_get_contents() tun.

War es hilfreich?

Lösung

Sie haben diese auf der PHP-Dokumentation Webseite, erste Kommentar unter der Funktionsreferenz:

function outputCSV($data) {
  $outstream = fopen("php://output", 'w');
  function __outputCSV(&$vals, $key, $filehandler) {
    fputcsv($filehandler, $vals, ';', '"');
  }
  array_walk($data, '__outputCSV', $outstream);
  fclose($outstream);
}

Und eine zweite Option:

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

Hope, das hilft!

BTW die PHP-Dokumente sollten immer die erste Adresse sein, wenn auf Figur Dinge zu versuchen. : -)

Andere Tipps

von einem Kommentar auf der PHP-Website

<?php
$out = fopen('php://output', 'w');
fputcsv($out, array('this','is some', 'csv "stuff", you know.'));
fclose($out);
?>

Da die ursprünglichen Fragesteller auf „Schreiben in den Browser on the fly“ wollten, vielleicht ist erwähnenswert (wie war mein Fall und niemand erwähnte es), dass, wenn Sie einen Dateinamen erzwingen und einen Dialog zu fragen, eine Datei herunterzuladen im Browser, müssen Sie die richtigen Header gesetzt, bevor irgendetwas mit fputcsv ausgibt:

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=myFile.csv');

eine CSV zu produzieren ist eigentlich gar nicht so schwer (ein CSV-Parsing ein bisschen mehr beteiligt ist).

Beispielcode einen 2D-Array als CSV für das Schreiben:

$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";
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top