CSVs without quotes not working with fgetcsv

ぃ、小莉子 提交于 2019-12-17 18:38:21

问题


I'm trying to parse CSV files uploaded by the user through PHP, but it's not working properly.

I've uploaded several properly formatted CSVs and it worked fine, however; I have many users trying to import CSV files exported from Excel and they are having problems. I've compared the files to mine and noticed that the Excel files all lack quotes around the entries. Aside from that, they are identical. If I open it and save it with Open Office, without making any changes at all it works. So I'm fairly certain it's related to the quotes.

My question is; how do I read these improperly formatted CSVs?

UPDATE: Cause has been found!

This is specific to the Mac version of Excel. Line breaks are handled differently on Macs for some arbitrary reason, so before using fgetcsv, you should do this;

ini_set('auto_detect_line_endings',TRUE);

回答1:


This is specific to the Mac version of Excel. Line breaks are handled differently on Macs for some arbitrary reason, so before using fgetcsv, you should do this;

ini_set('auto_detect_line_endings',TRUE);



回答2:


Looking at the manual page of fgetcsv, its prototype looks like this :

array fgetcsv  ( resource $handle  [, int $length  
    [, string $delimiter = ','  [, string $enclosure = '"' 
    [, string $escape = '\\'  ]]]] )

The default value for $enclosure (i.e. the 4th parameter) is a double-quote.

What if you try specifying that you don't want any enclosure, specifying an empty string for that 4th parameter ?

(Of course, this might break what's now working -- which means you'd have to deal with two separate cases : files with fields enclosed in double-quotes, and files that couldn't be read by the first case)



来源:https://stackoverflow.com/questions/2321064/csvs-without-quotes-not-working-with-fgetcsv

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!