zoukankan      html  css  js  c++  java
  • 彻底解决跨浏览器下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 ");
        }
  • 相关阅读:
    <数据结构基础学习>(四)链表 Part 2
    <Android基础> (四) Fragment Part 2
    swagger忽略方法里参数的方法
    ActiveMq
    Tomcat日志归档
    java代理的实现
    包装类型和基础类型是如何比较的
    hashmap
    可达性分析中,可以作为GcRoots的对象
    使用Navicat 连接oracle出现 “ORA-03135: Connection Lost Contact”
  • 原文地址:https://www.cnblogs.com/jiji262/p/2697205.html
Copyright © 2011-2022 走看看