Home >Backend Development >PHP Problem >What to do if php downloads excel with garbled characters
Solution to garbled php download excel: 1. Cancel the output of any non-file information during the download process; 2. Save the output excel format and suffix name consistent; 3. Use the "ob_clean" method to clear it buffer.
Recommended: "PHP Video Tutorial"
Write code and use PHP to download one I have uploaded This error occurs when Excel is good:
When forced to open, garbled characters appear.
After searching, there are two explanations:
1. Do not output any non-file information during the download process, such as echo log information. Otherwise, the downloaded file cannot be opened, prompting a format error or the file is damaged.
2. The output excel format must be consistent with the saved suffix name, otherwise it will prompt a format error or the file will be damaged.
So I changed the position of the a tag that I clicked to download, and checked the excel suffix name, but it had no effect.
Later, I searched and found that it might be a problem with the BOM header, because when opening a garbled file, there will be three characters "0xEF 0xBB 0xBF" in front of it. And PHP cannot recognize the BOM header.
Explanation of BOM header: In a utf-8 encoded file, the BOM is in the file header, occupying three bytes, and is used to indicate that the file belongs to utf-8 encoding. It is usually a string of hidden characters. Many software can recognize and ignore the BOM header, but PHP cannot.
Therefore, you can use editplus, ultraedit or WINHEX and other software to remove the BOM header from the files that need to be uploaded, and then upload them. If you have downloaded it, remove the BOM header and open it again.
In addition, you can also add a code: ob_clean() to your readfile and fread, that is, before the output, to clear the buffer.
The above is the detailed content of What to do if php downloads excel with garbled characters. For more information, please follow other related articles on the PHP Chinese website!