Home  >  Article  >  Backend Development  >  PHP附件下载中文名称乱码的解决方法_php技巧

PHP附件下载中文名称乱码的解决方法_php技巧

WBOY
WBOYOriginal
2016-05-16 20:02:48998browse

本文实例讲述了PHP附件下载中文名称乱码的解决方法。分享给大家供大家参考,具体如下:

PHP中,如果要下载的文件名称为中文,则会出现文件标题乱码。

此时就需要对标题进行编码,也就是说先进性urlencode,然后再放入header,然后问题就解决了。

$filename = urlencode("下载文档");
header ( "Content-disposition: attachment; filename=$filename.xls" );

网上说,在RFC2231的定义里面, 多语言编码的Content-Disposition应该这么定义:

复制代码 代码如下:
Content-Disposition: attachment; filename*="utf8''%E6%B5%8B%E8%AF%95.html"

即:

filename后面的等号之前要加 *
filename的值用单引号分成三段,分别是字符集(utf8)、语言(空)和urlencode过的文件名。

所以这时应该对文件名进行url编码转换 ,使用php的urlencode很轻松就搞定了

$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 . '"');
}

希望本文所述对大家PHP程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn