彻底解决跨浏览器下PHP下载文件名中的中文乱码问题

<?php

$ua = $_SERVER["HTTP_USER_AGENT"];

$filename = "中文 文件名.txt";
$encoded_filename = urlencode($filename);
$encoded_filename = str_replace("+", "%20", $encoded_filename);

header('Content-Type: application/octet-stream');

if (preg_match("/MSIE/", $ua)) {
    header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
} else if (preg_match("/Firefox/", $ua)) {
    header('Content-Disposition: attachment; filename*="utf8\'\'' . $filename . '"');
} else {
    header('Content-Disposition: attachment; filename="' . $filename . '"');
}

print 'ABC';
?>

上面是一个比较通用的解决方案(据说xp+IE7会有问题,未验证)。

这个问题是在使用CI-Excel-Generation-Library时遇到的,解决办法如下

  private function set_headers() {
        $ua = $_SERVER["HTTP_USER_AGENT"];
        $filename = $this->filename . ".xls";
        $encoded_filename = urlencode($filename);
        $encoded_filename = str_replace("+", "%20", $encoded_filename);     

        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        //header("Content-Type: application/vnd.ms-excel;charset=UTF-8");
        header("Content-Type: application/download");;
        if (preg_match("/MSIE/", $ua)) {  
            header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
        } else if (preg_match("/Firefox/", $ua)) {  
            header('Content-Disposition: attachment; filename*="utf8\'\'' . $filename . '"');
        } else {  
            header('Content-Disposition: attachment; filename="' . $filename . '"');
        }
        header("Content-Transfer-Encoding: binary ");
    }
原文地址:https://www.cnblogs.com/jiji262/p/2697205.html