[英]How to correct filename value in Content-Disposition header?
This piece of code NEARLY solves my issue saving a query to .csv
via php
– however I can't understand why when it prompts me to save as export.csv
, that file opens blank, while file.csv
saves perfectly at the same time with the data I need. 这段代码几乎解决了我通过php
将查询保存到.csv
问题–但是我不明白为什么当它提示我另存为export.csv
,该文件打开为空白,而file.csv
完美地保存了我需要的数据。 I'm sure it's something obvious going on with the headers. 我敢肯定,头文件是很明显的事情。 Can anyone help? 有人可以帮忙吗?
***EDIT below suggestions got me to this state and it no longer saves a file and prompts for a blank one but now the correct file shows with HTML crap in it. ***下面的建议编辑使我达到了这种状态,它不再保存文件并提示输入一个空白文件,但是现在显示了正确的文件,其中包含HTML废话。 There is no other HTML in this script -- I've tried suggestions from many other posts. 该脚本中没有其他HTML -我尝试了许多其他文章的建议。 How can I solve? 我该如何解决?
$query = "SELECT * from Table";
$result = mysqli_query($connS, $query);
$headers = $result->fetch_fields();
foreach($headers as $header) {
$head[] = $header->name;
}
$fp = fopen('php://output', 'w');
header('Content-Disposition: attachment; filename="export.csv"');
header('Content-Description: File Transfer');
header('Content-Type: text/csv');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
fputcsv($fp, array_values($head));
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
$fp = fopen('file.csv', 'w');
readfile($fp);
fclose($fp);
end();
You're currently only saving the contents to file, not sending it to the user's browser. 当前,您仅将内容保存到文件中,而不将其发送到用户的浏览器。 Perhaps try adding a call to readfile
before your die
statement. 也许尝试在die
语句之前添加对readfile
的调用。
So your last rows would look like this: 因此,您的最后一行将如下所示:
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
readfile($fp);
die;
}
Readfile reads a file and writes it to the output buffer. Readfile读取文件并将其写入输出缓冲区。 You can find more information on the readfile
function here . 您可以在此处找到有关readfile
函数的更多信息。
Note that the way you're currently doing it(saving to file before the user can download), if two users hit that page simultaneously, they would likely stomp on each others' toes(and create some odd intermix of the two created CSVs). 请注意,您当前的操作方式(先保存文件,然后用户才能下载),如果两个用户同时点击该页面,他们可能会mp脚others脚(并在创建的两个CSV中产生一些奇怪的混合) 。 You may want to try simply outputting the CSV contents directly to the user's browser , using the code in the accepted answer there. 您可能想要尝试使用此处接受的答案中的代码将CSV内容直接直接输出到用户的浏览器 。 If you do that after your headers, it should result in the browser treating it like a file to be downloaded. 如果在标头之后执行此操作,则浏览器应将其视为要下载的文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.