2

是否可以即时创建 file.txt 下载它?

该文件应该存储在其中,backup/process/_pro_links_date.txt 但是当我下载该文件时,它没有 .txt 扩展名,并且存储在我的文件夹中。

HTML

<a href="?down=load">File</a>

PHP

if ( $_GET['down'] == 'load' ) {
$date = date( 'Y-m-d H:i:s' );

$myFile = "backup/process/_pro_links_$date.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Title - Url - Live Date - Process Date \r";
fwrite($fh, $stringData);
$sql = mysql_query("SELECT * FROM k_addlinks WHERE user_code = '".$_SESSION['user_code']."' ") or die (mysql_error());
while ($row = mysql_fetch_array($sql)){
$dated = date("m/j/y g:i",strtotime( $row["date"] ));
    if($row["spider_date"] == 'never'){
        $sdate = $row["spider_date"];
    }else{
        $sdate = date("m/j/y g:i",strtotime( $row["spider_date"] ));
    }
    $stringData = $row['pro_name'] . $row['customDomain'] . $dated . $sdate . '\r';
}
fwrite($fh, $stringData);
fclose($fh);

$path = "backup/process/_pro_links_$date.txt";
$name = "_pro_links_$date.txt";
header("Content-Type: text/plain");
header("Content-Length: " . filesize($path));    
header('Content-Disposition: attachment; filename='.$name);

readfile($path);
}

我的代码有什么问题?

4

3 回答 3

2

我看到了这个问题。在您的Content-Disposition标题中,您设置了文件名,但您的文件名包含空格,因为您使用date("Y-m-d H:i:s"). 因此,您需要在该标头中用引号将文件名括起来:

// $name contains a space, in the format _pro_links_Y-m-d H:i:s.txt
$name = "_pro_links_$date.txt";
// Surround the filename with quotes...
header('Content-Disposition: attachment; filename="'.$name . '"');

$date或者,在文件名中使用它之前删除空格:

$date = str_replace($date, " ", "_");
$name = "_pro_links_$date.txt";
于 2012-09-09T13:47:02.987 回答
1

与其将其保存到文件中,不如在发送标头后回显它。

于 2012-09-09T13:40:36.033 回答
1
$content = "Hello world !!!";
$name = "name.txt";

$file = fopen($name,"wb");
fwrite($file, $content);
fclose($file);

header('Content-Type: charset=utf-8');
header("Content-disposition: attachment; filename=$name");

print $content; 
于 2015-01-06T22:53:07.213 回答