doufu5401 2018-04-18 14:13
浏览 24
已采纳

创建文本文件,并让用户选择下载PHP

I need to give the user the option to save the result of a query in a text file and download it.

Now, I have this code:

 while ($row = mysqli_fetch_array($resulta)){
    echo "<tr>";
    echo "<td class='cell0'><a href='Visualizar_Disciplina.php?nome=" .$row['nome'] . "'>" . $row['nome'] . " </a></td>";
    echo "<td class='cell0'>" . $row['nomeprofessor'] . "</td>";
    echo "<td class='cell0'>" . $row['creditos'] . "</td>";
    echo "</tr>";
    } 

And I don't know what should I do to create the text file in the server and then, when the user hit a button, the file will be downloaded.

How can I do that?

Thanks!

  • 写回答

1条回答 默认 最新

  • douzhang2680 2018-04-18 14:25
    关注

    You basically have two alternatives.

    Alternative 1

    Store the file on the server, and make sure the user can access the raw file via some URL. You probably want to have some logic for cleaning up files as each new download would add a new file on the server, which eventually will run out of space.

    <?php
    $uri = tempnam("/dir/for/files");
    $myfile = fopen($uri, "w") or die("Unable to open file!");
    
    while ($row = mysqli_fetch_array($resulta)){
       $out  = "<tr>
    ";
       $out .= "<td class='cell0'><a href='Visualizar_Disciplina.php?nome=" .$row['nome'] . "'>" . $row['nome'] . " </a></td>
    ";
       $out .= "<td class='cell0'>" . $row['nomeprofessor'] . "</td>
    ";
       $out .= "<td class='cell0'>" . $row['creditos'] . "</td>
    ";
       $out .= "</tr>
    ";
       fwrite($myfile, $out);
    }
    fclose($myfile);
    ?>
    

    Now the file is written to the server and you can point your client to the url corresponding to that file.

    Alternative 2

    Place a download.php file somewhere that will "generate" the content to be downloaded on the fly. In order for the browser of your user to accept the file as a download rather then as displayable content you need to set the appropriate headers at the top of download.php

     <?php
     header('Content-type: text/plain');
     header('Content-Disposition: attachment; filename="filename.txt"');
     header('Expires: 0');
     header('Cache-Control: must-revalidate');
     header('Pragma: public');
    
     while ($row = mysqli_fetch_array($resulta)){
        echo "<tr>
    ";
        echo "<td class='cell0'><a href='Visualizar_Disciplina.php?nome=" .$row['nome'] . "'>" . $row['nome'] . " </a></td>
    ";
        echo "<td class='cell0'>" . $row['nomeprofessor'] . "</td>
    ";
        echo "<td class='cell0'>" . $row['creditos'] . "</td>
    ";
        echo "</tr>
    ";
     }
     exit;
     ?>
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部