php fgetcsv 无法读取以 mac 格式的 csv 文件结尾的行,有更好的解决方案吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4541749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 13:23:41  来源:igfitidea点击:

fgetcsv fails to read line ending in mac formatted csv file, any better solution?

phpfgetcsv

提问by Musa

I was parsing a csv file using php with fgetcsv function. It parsed all content in a line, later i found, csv contains carraige return as "\r". I saw - it was reported as php bug before. I've solved this by setting php runtime configuration which is -

我正在使用带有 fgetcsv 函数的 php 解析 csv 文件。它解析了一行中的所有内容,后来我发现,csv 包含 carraige 返回为“\ r”。我看到了 - 它之前被报告为 php 错误。我已经通过设置 php 运行时配置解决了这个问题 -

ini_set("auto_detect_line_endings", "1");

is there any more solution or is this the right way?

有没有更多的解决方案或者这是正确的方法?

Thanks

谢谢

回答by phihag

Setting auto_detect_line_endingsis explicitly recommended by the php documentation.

php 文档auto_detect_line_endings明确推荐设置。

However, I cannot fathom why you would want to delimit lines with \rin 2010. If possible, convert them to the UNIX-style \n.

但是,我无法理解为什么要\r在 2010 中分隔行。如果可能,请将它们转换为 UNIX 样式的\n.

回答by spekary

\rline endings are created by Microsoft Excel when saving as a CSV file, so there is not much getting around that if you are starting with an Excel spreadsheet.

\r当另存为 CSV 文件时,行结尾由 Microsoft Excel 创建,因此如果您从 Excel 电子表格开始,则没有太多解决方法。

Using auto_detect_line_endingsworks fine, or you can normalize line endings with preg_replace("/\r\n|\n\r|\n|\r/", "\n", $subject);

使用auto_detect_line_endings工作正常,或者您可以使用preg_replace("/\r\n|\n\r|\n|\r/", "\n", $subject);