Home >Backend Development >PHP Tutorial >How to solve garbled characters in PHP download file names_PHP Tutorial
By setting Content-Type to application/octet-stream, dynamically generated content can be downloaded as a file. I believe everyone knows this. Then use Content-Disposition to set the downloaded file name. Many people know this. Basically, the download program is written like this:
<?php<br />$filename = "document.txt";<br />header(Content-Type: application/octet-stream);<br />header(Content-Disposition: attachment; filename= . $filename);<br /><br />print "Hello!";<br />?>
After opening it with a browser, you can download document.txt.
However, if $filename is UTF-8 encoded, some browsers cannot handle it properly. For example, slightly change the above program:
<?php<br />$filename = "中文 文件名.txt";<br />header(Content-Type: application/octet-stream);<br />header(Content-Disposition: attachment; filename= . $filename);<br /><br />print "Hello!";<br />?>
If you save the program in UTF-8 encoding and then access it again, the file name downloaded by IE6 will be garbled. The file name downloaded under FF3 only has the word "Chinese". Everything works fine under Opera 9.
The output header actually looks like this:
Content-Disposition: attachment; filename=中文 文件名.txt
In fact, according to the definition of RFC2231, the Content-Disposition of multi-language encoding should be defined like this:
Content-Disposition: attachment; filename*="utf8%E4%B8%AD%E6%96%87%20%E6%96%87%E4%BB%B6%E5%90%8D.txt"
i.e.:
After testing, it was found that the support of several mainstream browsers is as follows:
IE6 | attachment; filename=" |
FF3 | attachment; filename="UTF-8文件名" |
attachment; filename*="utf8 |
|
O9 | attachment; filename="UTF-8文件名" |
Safari3(Win) | 貌似不支持?上述方法都不行 |
It seems that the program must be written like this to support all major browsers:
<?php<br /><br />$ua = $_SERVER["HTTP_USER_AGENT"];<br /><br />$filename = "中文 文件名.txt";<br />$encoded_filename = urlencode($filename);<br />$encoded_filename = str_replace("+", "%20", $encoded_filename);<br /><br />header(Content-Type: application/octet-stream);<br /><br />if (preg_match("/MSIE/", $ua)) {<br /> header(Content-Disposition: attachment; filename=" . $encoded_filename . ");<br />} else if (preg_match("/Firefox/", $ua)) {<br /> header(Content-Disposition: attachment; filename*="utf8\ . $filename . ");<br />} else {<br /> header(Content-Disposition: attachment; filename=" . $filename . ");<br />}<br /><br />print ABC;<br />?><br>