我正在尝试使用此代码解析 csv 文件
if (($handle = fopen($csvFilePath, "r")) !== FALSE) {
$c=0;
$string="";
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($c>0)
{
if(($data[$email]!="") and ($data[$firstname]!="") and ($data[$lastname]!=""))
{
$string.='(1,';
$string.="'".$data[$email]."',";
$string.="'".$data[$firstname]."',";
$string.="'".$data[$lastname]."',";
$string.="'".Yii::app()->params['clientimporttext']."'";
$string.='),';
}
}
$c++;
}
fclose($handle);
}
它在 windows csv 上运行良好。
但是当我从 mac 创建 csv 并解析时它不起作用。(它无法识别行尾),
此外,当我使用 mac 打开相同的 Windows csv 并使用相同的代码进行解析时,它不起作用。
但是当我将其保存为 windows csv 时。它再次起作用。
那么实际上 mac csv 和 windows csv 之间有什么区别?
这两个的分隔符不同吗?
我应该如何更改代码以使其同时适用于两者?
最佳答案
答案在 PHP 文档注释中:
http://be2.php.net/manual/en/function.fgetcsv.php
Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.
问题在于 Windows 和类 UNIX 机器(如您的 Mac)上的行结尾之间的差异:windows ='\r\n'
和 unix = '\n '
解决方案:在打开文件之前添加这一行:
ini_set('auto_detect_line_endings',TRUE);
关于php - windows csv 和 mac csv 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45736078/