带字节数组的 ZF2 流

ZF2 Stream with byte array

我从 REST API 得到一个字节数组。然后我从这个字节数组创建一个本地文件。我可以用 ZF2 将这个文件发送到浏览器。

ZF2 控制器操作中的代码:

file_put_contents($fullpath, $rawPdf);
 $headers = new \Zend\Http\Headers();
 $contentDisposition = ($view == 'inline') ? 'inline': 'attachment';
 $headers->addHeaders(array(
    'Content-Disposition' => $contentDisposition . '; filename="' . basename($fullpath) . '"',
    'Content-Type' => 'application/pdf',
    'Content-Length' => filesize($fullpath),
    'Expires' => '@0',
    'Cache-Control' => 'must-revalidate',
    'Pragma' => 'public'
 ));
$response = new \Zend\Http\Response\Stream();
$response->setStream(fopen($fullpath, 'r'));
$response->setStreamName(basename($fullpath));
$response->setStatusCode(200);
$response->setHeaders($headers);
return $response;

但我会直接将字节数组发送到浏览器而不创建本地文件

如何使用字节数组设置流($response->setStream())?如何使用字节数组创建资源,但不创建本地文件?

用普通的旧PHP我可以做到:

$rawPdf = '';
array_walk($byteArray, function($value) use (&$rawPdf) {
    $rawPdf .= chr($value);
});
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="Bericht.pdf"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
echo $rawPdf;

这是我用来将一些数据导出到 CSV 文件并自动下载的代码的简化示例。

您可以根据需要调整它

header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename="csv_file.csv');
header('Cache-Control: max-age=0');

$file = fopen('php://output', 'w');

foreach ($this->getData() as $data)
{
     fputcsv($file, $data);
}

fclose($file);
exit(0);