Home > Article > Backend Development > PHP file download Chinese file name garbled
This article mainly introduces the garbled Chinese file name of PHP file download. Interested friends can refer to it. I hope it will be helpful to everyone.
In PHP, if the name of the file to be downloaded is Chinese, the file title will be garbled.
At this point, you need to encode the title, which means advanced urlencode, and then put the header in, and then the problem is solved.
$filename = urlencode("下载文档"); header ( "Content-disposition: attachment; filename=$filename.xls" );
It is said online that in the definition of RFC2231, the Content-Disposition of multi-language encoding should be defined like this:
The code is as follows:
Content-Disposition: attachment; filename*="utf8''%E6%B5%8B%E8%AF%95.html"
That is:
The equal sign after filename must be preceded by *
The value of filename is divided into three segments with single quotes, which are character set (utf8), language (empty) and urlencoded file name.
So at this time, the file name should be converted to URL encoding. It can be easily done using php's 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 . '"'); }
Summary: The above is the entire content of this article, I hope it can It will be helpful to everyone’s study.
Related recommendations:
Detailed explanation of the principles and examples of chain operation in PHP
How to use PHP to access Alipay’s instant payment function
php method to realize the manipulation of mysqli database
The above is the detailed content of PHP file download Chinese file name garbled. For more information, please follow other related articles on the PHP Chinese website!