Home>Article>Backend Development> How to solve the problem of garbled file names generated by php
Solutions to garbled file names generated by php: 1. Replace all numbers with " "; 2. Add "header("Content-type: application/vnd.ms-excel");"; 3. , Delete the spaces on both sides of "filename=xxx".
The operating environment of this article: Windows 7 system, PHP version 7.1, DELL G3 computer
Solution to garbled PHP export file name
Problem scenario:
Statistical data needs to be added with a everywhere excel function, so I used composer to install the phpspreadsheet component, process the data and export it. When encountering ASCII named file names, everything is exported normally, but when encountering Chinese file names, the exported file names are garbled.
The solution is posted directly here:
1. File name processing
Because PHP’s urlencode function will Various whitespace characters are transcoded into numbers. This number will not be escaped in either Chrome or Firefox.
, so here all the numbers are replaced again with
$file_name = '导出文件.xls'; // 这是原本要导出的文件名 $encoded_filename = url_encode($file_name);// 将文件名进行urlencode转码 $encoded_filename = str_replace('+', '%20', $encoded_filename);
2 .Header file: File type declaration
If the export is a file and it is not a certain excel type, use file header No.1
I exported an xls under excel Format table, so I am using file header No.2
// 文件头No.1: 告诉浏览器这里要有一个文件流输出 header("Content-type: application/octet-stream"); // 文件头No.2: 告诉浏览器这里要输出一个excel文件 header("Content-type: application/vnd.ms-excel");
Header file: Download file name declaration
This step is key, there are two requirements Things to note
Whether it is filename=xxx or filename*=xxx, there should be no spaces on both sides of the equal sign
filename*=xxx. This configuration item actually consists of 3 parts, namely Character set (utf8), language (empty) and urlencoded file name, where language is an empty string, enclosed in single quotes, and there should be no spaces between the three parts.
header('Content-Disposition: attachment; filename="foo-%c3%a4.xls"; filename*=UTF-8\'\'foo-%c3%a4.xls');
I used the above code to test chrome, firefox, 360, and ie11 and all worked well. Hope it helps you too.
[Recommended learning:PHP video tutorial]
The above is the detailed content of How to solve the problem of garbled file names generated by php. For more information, please follow other related articles on the PHP Chinese website!