如何添加支持以在php页面上下载文件?
我们希望在我们的php页面上支持一个特性,当用户单击页面上的按钮时,我们将自动生成一些数据到文件中,并将文件下载到客户端。现在很多网站都有这样的功能(例如,下载chrome image以安装在客户端机器上),如何在php中实现这一功能?在php页面上,使用按钮触发打开要写入的文件并发送到浏览器下载(例如.CSV文件):如何添加支持以在php页面上下载文件?,php,download,Php,Download,我们希望在我们的php页面上支持一个特性,当用户单击页面上的按钮时,我们将自动生成一些数据到文件中,并将文件下载到客户端。现在很多网站都有这样的功能(例如,下载chrome image以安装在客户端机器上),如何在php中实现这一功能?在php页面上,使用按钮触发打开要写入的文件并发送到浏览器下载(例如.CSV文件): $(“#下载_文件”)。单击(函数(){ open(“generate_a_csv_file.php”,“_blank”); }); 然后创建另一个将生成内容的php文件,使
$(“#下载_文件”)。单击(函数(){
open(“generate_a_csv_file.php”,“_blank”);
});
然后创建另一个将生成内容的php文件,使用头告诉浏览器将内容作为文件发送(在本例中,将生成一个名为“example_file.csv”的文件供下载):
注意:确保不在“标题”行上方输出任何内容。必须先输出头文件,然后再输出其他文件。您的请求有点模糊(“生成一些数据”),但它将是这样的。我很抱歉,您的数据来自SQL查询:
<?php
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename=YOUR_EXPORT.txt");
header("Pragma: no-cache");
header("Expires: 0");
$fp = fopen('php://output', 'w');
$your_query = mysql_query( "select * from bla bla bla ... ");
while( $codes = mysql_fetch_array( $your_query ) ) {
$row = array();
$row[] = some data ...
fputs($fp, $row);
}
fclose($fp);
谢谢!但“下载”文件是如何触发的呢?我的意思是我看不到按钮和脚本之间的联系。。。
<?php
header('Content-disposition: attachment; filename=example_file.csv');
header('Content-type: application/force-download');
echo "line1,abc,123"."\r\n";
echo "line2,xyz,456"."\r\n";
?>
<?php
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename=YOUR_EXPORT.txt");
header("Pragma: no-cache");
header("Expires: 0");
$fp = fopen('php://output', 'w');
$your_query = mysql_query( "select * from bla bla bla ... ");
while( $codes = mysql_fetch_array( $your_query ) ) {
$row = array();
$row[] = some data ...
fputs($fp, $row);
}
fclose($fp);