为什么无法通过 PhpOffice\PhpSpreadsheet 读取 csv 文件?

时间:2020-12-23 08:41:13

标签: php phpoffice-phpspreadsheet

我正在使用 PhpOffice\PhpSpreadsheet 读取 csv 文件,例如:

$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile($file);
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load($file);

错误:Warning: mime_content_type(): Can only process string or stream arguments

但它适用于 xlsx 文件。

我尝试使用 PhpOffice\PhpSpreadsheet\Reader\Csv 但它是同样的错误。 我尝试转储 $file,我看到 mimeType 是 text/csv,但是当 $file->getMimeType() 返回 text/plain 时。这使我无法验证上传文件(我只允许用户上传 xlsx/csv 文件)。我认为这可能导致错误无法读取 csv 文件?

编辑:这是我的错。 load() 以字符串形式接收参数,但我传递了一个 Symfony\Component\HttpFoundation\File\UploadFile(因为它适用于 xlsx 文件)。因此,将 $file 更改为 $file->getPathName() 并且效果很好。 但是对于验证文件,我想我必须接受文本/纯文本,有人知道吗?

1 个答案:

答案 0 :(得分:0)

您可以使用 $file->getClientMimeType() 方法检查文件 MIME 类型。这将为您提供您正在寻找的“text/csv”字符串。