【问题标题】:Download file from server to clients system via php通过php将文件从服务器下载到客户端系统
【发布时间】:2013-09-06 15:33:53
【问题描述】:

我正在使用以下脚本通过 PHP 下载文件:

header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename=sale.csv');
    header("Content-Transfer-Encoding: binary");
    header('Expires: 0');
    header('Pragma: no-cache');
    header("Content-Length: ".filesize($CSVFileName));
        readfile($CSVFileName);

$CSVFilename 值为“/home/demo/public_html/testwordpress/csv/sale.csv” 也试过 header("Content-type: text/csv");

不知何故,它没有下载路径上给出的 csv 文件。它正在以 csv 格式下载页面的源代码。 这是我得到的代码:

<!DOCTYPE html>
<!--[if IE 6]>
<html id="ie6" lang="en-US">
<![endif]-->
<!--[if IE 7]>
<html id="ie7" lang="en-US">
<![endif]-->
<!--[if IE 8]>
<html id="ie8" lang="en-US">
<![endif]-->
<!--[if !(IE 6) | !(IE 7) | !(IE 8)  ]><!-->
<html lang="en-US">
<!--<![endif]-->
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<title>Call Details | Test</title>
<link rel="profile" href="http://gmpg.org/xfn/11" />

请指教

【问题讨论】:

  • $CSVFileName 是在哪里指定的?
  • 你能告诉我们下载的文件是什么样的吗?
  • 如果将内容类型标头更改为header("Content-type: text/csv");会发生什么
  • 您的内容类型不应有引号。这是Content-type: application/octet-stream

标签: php


【解决方案1】:

我在这里可能有点不习惯,但有一种更简单的方法(我想!)来简单地下载文件。

$file = "/home/demo/public_html/testwordpress/csv/sale.csv";
$contents = file_get_contents($file);

// Manipulate the contents however you wish.
$newFilePath = "somewhere/over/the/rainbow/sale.csv";
file_put_contents($newFilePath, $contents);
  • file_get_contents 也适用于 http 流。

【讨论】:

    【解决方案2】:

    我是这样弄的:

    <?PHP
        $filename= "yourfilepath.csv";
    
        header("Content-Disposition: attachment; filename=\"$filename\"");
        header("Content-Type: application/vnd.ms-excel");
    
        echo "your content to the .csv file";
    ?>
    

    【讨论】:

    • 你试过只使用我给你的标题吗?
    • 好吧,我修改并重新编辑了代码,只需通过复制粘贴即可工作(它只需要 php 标签)。请注意,您不会使用此方法输出现有文件,而是在用户下载文件时创建和写入它。
    猜你喜欢
    • 1970-01-01
    • 2016-02-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 2014-03-30
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多