-1

我们希望在我们的 php 页面上支持一个功能,这样当用户单击页面上的按钮时,我们会自动将一些数据生成到文件中并将文件下载到客户端。今天很多网站都有这样的功能(例如,下载chrome图像安装在客户端机器上),如何在php中实现?

4

2 回答 2

1

您的请求有点模糊(“生成一些数据”),但它会是这样的。我在说你的数据来自 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);
于 2013-05-26T03:12:08.517 回答
0

在带有按钮的 php 页面上,让按钮触发器打开您要写入的文件并发送到浏览器进行下载(例如 .CSV 文件):

            <html>
            <head>
               <!-- Using jquery -->
               <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
               <script>
                   $("#download_file").click(function(){ 
                        window.open("generate_a_csv_file.php","_blank");
                   });
               </script>
            </head>

            <body>
                <input type="button" value="Download CSV File">
            </body>
            </html>

然后创建另一个将生成内容的 php 文件,使用标题告诉浏览器将内容作为文件发送(在此示例中,将生成名为“example_file.csv”的文件以供下载):

    <?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";  

    ?>

注意:确保您没有在“标题”行上方输出任何内容。标头必须在其他任何内容之前输出。

于 2013-05-26T01:47:02.487 回答