PHP强制下载.xlsx文件损坏 [英] PHP force downloading .xlsx file corrupt

查看:681
本文介绍了PHP强制下载.xlsx文件损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个允许教师上传文件和学生下载文件的网站。但是,有一个问题。 Microsoft Word(.docx)文件完美下载,但是当下载一个excel(xlsx)文件时,excel会给出一个这个文件已损坏,无法打开对话框。我的下载代码如下:

 



code> case'xlsx':

header('Content-type:application / vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition:attachment; filename ='。$ filename。'');
header('Content-Transfer-Encoding:binary');
header('Expires:0');
header('Pragma:no-cache');
readfile('./ uploads / resources / courses /'。$ filename);

break;


解决方案

我有这个问题,是 BOM



如何注意



解压缩:使用解压缩检查输出文件,我在第二行看到一个警告。

  $ unzip -l file.xlsx 
存档:file.xlsx
警告文件:3个额外的字节开头或zip文件
...

xxd(十六进制查看器):我看到前5个字节,带有以下命令

  head -c5 file.xlsx | xxd -g 1 
0000000:ef bb bf 50 4b PK ...

注意3个第一个字节 ef bb bf 这是BOM!



为什么?



也许是一个带有BOM或一个库的先前输出的php文件。



你必须找到文件或命令与BOM在哪里,在我的情况现在,我没有时间找到它,但是我用输出缓冲区来解决这个问题。

 <?php 
ob_start();

// ...代码,包括,etc

ob_get_clean();
// headers ...
readfile($ file);


I am working on a site that allows teachers to upload documents and students download them. However, there is a problem. Microsoft Word (.docx) files download perfectly, but when downloading an excel (xlsx) file, excel gives a "This file is corrupt and cannot be opened" dialog. Any help with this would be greatly appreciated!

My download code is as follows:

case 'xlsx':

    header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Pragma: no-cache');
    readfile('./uploads/resources/courses/' . $filename);

break;

解决方案

I have this problem and was the BOM.

How to notice it

unzip: Checking the output file with unzip, I saw a warning at the second line.

$ unzip -l file.xlsx 
Archive:   file.xlsx
warning file:  3 extra bytes at beginning or within zipfile
...

xxd (hex viewer): I saw the first 5 bytes with the following command

head -c5 file.xlsx | xxd -g 1
0000000: ef bb bf 50 4b                             PK...

Notice the 3 first bytes ef bb bf that's BOM!

Why?

Maybe a php file with BOM or a previous output from a library.

You have to find where is the file or command with the BOM, In my case and right now, I don't have time to find it, but I solve this with output buffer.

<?php
ob_start();

// ... code, includes, etc

ob_get_clean();
// headers ...
readfile($file);

这篇关于PHP强制下载.xlsx文件损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆