我在数据库中导入数据,并且我想在文本文件中向用户提供一些错误/反馈,但我不确定如何处理它。我的代码很长,所以我将一个示例代码写入文件
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
在这种情况下,我希望&#34; John Doe&#34;在我的文件中两次并上传到屏幕以便用户可以下载
答案 0 :(得分:1)
您可以使用php readfile()
将文件发送到输出缓冲区。您可以查看php文档以获取有关如何执行此操作的示例。 Readfile()
样本看起来像这样
if (file_exists($myfile)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($myfile).'"');
header('Cache-Control: must-revalidate');
header('Content-Length: ' . filesize($myfile));
readfile($myfile);
exit;
}
答案 1 :(得分:0)
您可能想尝试下面的代码段:
<?php
$fileName = "data-log.txt";
// IF THE FILE DOES NOT EXIST, WRITE TO IT AS YOU OPEN UP A STREAM,
// OTHERWISE, JUST APPEND TO IT...
if(!file_exists($fileName)){
$fileMode = "w";
}else{
$fileMode = "a";
}
// OPEN THE FILE FOR WRITING OR APPENDING...
$fileHandle = fopen($fileName, $fileMode) or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($fileHandle, $txt);
$txt = "Jane Doe\n";
fwrite($fileHandle, $txt);
fclose($fileHandle);
// PUT THE FILE UP FOR DOWNLOAD:
processDownload($fileName);
function processDownload($fileName) {
if($fileName){
if(file_exists($fileName)){
$size = @filesize($fileName);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $fileName);
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $size);
readfile($fileName);
exit;
}
}
return FALSE;
}
?>