dongzhang5006 2017-04-26 21:26
浏览 11

如何将文本输出到文件?

Here's my current code:

$link = mysqli_connect("localhost", "username", "password", "database");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s
", mysqli_connect_error());
    exit();
}

$query = "SELECT id, title FROM titles WHERE type = 'movie' ORDER BY id ASC";

if ($result = mysqli_query($link, $query)) {

    while ($row = mysqli_fetch_assoc($result)) {
        printf ("%s-%s
", $row["id"], $row["title"]);
    }

    mysqli_free_result($result);
}

mysqli_close($link);

Using printf is correctly printing all the rows from my MySQL table.

However, instead of printing it, I want to write it to a text file. Is this possible to do with printf or should I be doing something else?

  • 写回答

3条回答 默认 最新

  • dousui8263 2017-04-26 21:38
    关注

    if you want to write it to the disk, on the server, you should look into fopen(), fwrite() and fclose()

    also you could use file_put_contents, but that would require you to prepare all the content before writing it to the file (which could lead to high memory usage if you have lots of records) or if you go with the "append" mode, writing 1 line at a time, you'll have all the overhead of opening and closing the file each time

    if you want to make the browser download it, instead of just showing the content, then you need to add a header to the response

    header('Content-Disposition: attachment; filename="'.$filename.'"');
    

    preferably adding some content type before it. for example, in your case:

    header('Content-type: text/plain');
    
    评论

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行