Home  >  Article  >  Backend Development  >  How to solve the garbled problem of Excel downloaded by PHP

How to solve the garbled problem of Excel downloaded by PHP

藏色散人
藏色散人Original
2020-08-06 10:34:452262browse

Solution to php downloading excel garbled code: 1. Do not output any non-file information during the download process; 2. Save the output excel format and suffix name consistent; 3. Use the "ob_clean()" function Clear the buffer.

How to solve the garbled problem of Excel downloaded by PHP

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 How to solve the garbled problem of Excel downloaded by PHP. For more information, please follow other related articles on the PHP Chinese website!

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