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
fgetcsv fails to read line ending in mac formatted csv file, any better solution?
提问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_endings
is explicitly recommended by the php documentation.
php 文档auto_detect_line_endings
明确推荐设置。
However, I cannot fathom why you would want to delimit lines with \r
in 2010. If possible, convert them to the UNIX-style \n
.
但是,我无法理解为什么要\r
在 2010 中分隔行。如果可能,请将它们转换为 UNIX 样式的\n
.
回答by spekary
\r
line 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_endings
works 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);