首页 > 解决方案 > php网站显示文件而不是下载

问题描述

我在 Azure 的 linux Web 应用服务上运行 php 8 网站。当用户按下按钮时,我想动态创建一个文件(从 db 读取数据)并下载它。相反,它在页面上显示内容。这是代码

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Type: text/csv; charset=utf-8');
header("Content-Disposition: attachment; filename=geodata.csv");
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize("geodata.csv"));

$file = fopen('php://output', 'w') 
            or die ("Unable to create file in write mode");
if (ob_get_contents()) ob_end_clean();
    fputcsv($output, array('name','loc','zip'), chr(6));
    $mrows = mysqli_query($myconnection, "SELECT name,loc,zip FROM geo_tbl WHERE sp = 'FL'");
    while ($mrow = mysqli_fetch_assoc($mrows)) {
        fputcsv($file, $mrow, chr(6));
    }
    fclose($file);
    readfile("geodata.csv");
    exit();

谢谢

标签: phplinuxazure-web-app-service

解决方案


当用户按下按钮时

只需将下载属性添加到您的按钮,它应该可以立即工作。

<a href="link/to/your/file.csv" download="filename.csv">Download link</a>

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-download


推荐阅读