duanqinqiao4844 2009-06-24 19:28
浏览 223
已采纳

在php中将文件从Linux下载到Windows时修复文件编码

Ok I have an issue. I have a Linux web server (RHEL 4 with apache 2) that is used to house an application. Part of this application is a set of php scripts. I created a script that accepts some form variables and then downloads a file to the user. Here si the code:

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$destFileName);
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($fullPath));
ob_clean();
flush();
readfile($fullPath);

This all works fine, and the file gets downloaded. But there is a problem. These files are being downloaded from the Linux box, to a Windows machine (ALWAYS). The problem is the encoding. When you look at the file on the Linux box all the text is aligned and all the columns look fine. (The files are just flat text files). But when the file gets downloaded onto the Windows box, and opened in Notepad, the file is all fouled up, and nothing is aligned. You also see weird charactors (the ones that look like a box, but that is just the generic representation for the unknow charactor). When this file is imported into another program, it does not work.

However, when I open the file up in WordPad, all the text look correct. If I save it from wordpad it will import correctly, and look correct in Notpad.

I don't have much knowlege on file encoding, so any information on how I can encode the file before sending to the user for download would be great.

I did try replacing the readfile($fullPath); with:

$handle = @fopen($fullPath, "r");
if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle);
        $buffer = str_replace('
', '
', $buffer);
        echo $buffer;
    }
    fclose($handle);
}

Thanks!

  • 写回答

3条回答

  • duanhuayong6687 2009-06-24 21:06
    关注

    There's an issue with the following line:

    $buffer = str_replace('
    ', '
    ', $buffer);
    

    You'd need to use double quotes there. " " is newline. ' ' is the literal char sequence backslash-n:

    # php -r "var_dump('
    ', \"
    \");"
    string(2) "
    "
    string(1) "
    "
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决