PHP创建文本文件即时下载文件是可能的吗?

时间:2012-09-09 13:38:13

标签: php fwrite

是否有可能即时创建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);
}

我的代码出了什么问题?

3 个答案:

答案 0 :(得分: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";

答案 1 :(得分:0)

不是将其保存到文件中,而是在发送标题后回显它。

答案 2 :(得分:0)

$content = "Hello world !!!";
$name = "name.txt";

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

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

print $content;