Подтвердить что ты не робот

PHP Создайте несколько CSV файлов в памяти, затем сжимайте

У меня есть требование создать 3 файла CSV (в памяти) во время одного HTTP-запроса, ZIP файлы в один сжатый файл и вернуть сжатый файл в качестве ответа HTTP.

У меня есть следующий код для создания zip файла...

$files = array($file1, $file2);
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
    $zip->addFile($file);
}
$zip->close();

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);

Однако я не знаю, как создавать CSV файлы в памяти.

Как я могу это достичь?

4b9b3361

Ответ 1

Попробуйте это...

// some data to be used in the csv files
$headers = array('id', 'name', 'age', 'species');
$records = array(
    array('1', 'gise', '4', 'cat'),
    array('2', 'hek2mgl', '36', 'human')
);

// create your zip file
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);

// loop to create 3 csv files
for ($i = 0; $i < 3; $i++) {

    // create a temporary file
    $fd = fopen('php://temp/maxmemory:1048576', 'w');
    if (false === $fd) {
        die('Failed to create temporary file');
    }

    // write the data to csv
    fputcsv($fd, $headers);
    foreach($records as $record) {
        fputcsv($fd, $record);
    }

    // return to the start of the stream
    rewind($fd);

    // add the in-memory file to the archive, giving a name
    $zip->addFromString('file-'.$i.'.csv', stream_get_contents($fd) );
    //close the file
    fclose($fd);
}
// close the archive
$zip->close();


header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);

// remove the zip archive
// you could also use the temp file method above for this.
unlink($zipname);

Я только что протестировал это на своей машине, и он отлично работает.

Я использовал эту ссылку в качестве ссылки, она может быть полезна.

Ссылка MetaShock

Ответ 2

Вы можете использовать php обертка памяти:

$zipname = 'php://memory';

В системах с файловой системой /dev/shm вы можете создавать там файлы, они будут храниться только в памяти и доступны только для текущего процесса. Не забудьте удалить их после отправки, процесс веб-сервера будет продолжать работать.