Вопрос

Мне нужен способ сделать fputscv Функция записи данных в браузер на лету вместо создания временного файла, сохранения данных в этот файл и выполнения echo file_get_contents().

Это было полезно?

Решение

Нашел это на веб -сайте PHP DOCS, первый комментарий под ссылкой на функцию:

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

И второй вариант:

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

Надеюсь это поможет!

Кстати, документы PHP всегда должны быть вашей первой остановкой, пытаясь выяснить вещи. :-)

Другие советы

Комментарий к сайту PHP

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

Как хотел отметить оригинальный Asker «написать в браузер на лета , вы должны установить правильные заголовки, прежде чем fputcsv:

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

Производство CSV на самом деле не так сложно (анализ CSV немного более вовлечен).

Пример кода для написания 2D массива в качестве 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";
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top