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 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算