在PHP处理CSV文件,能够满足MS和UNIX换行符的要求
问题说明
我有一个处理CSV文件作为输入的模块。
I have a module that process a CSV File as Input. It works fine in my Ubuntu machine, until someone in my team start to use Microsoft Excel to create the csv.
结果是,新输入的CSV具有^ M (\r\n)字符,因此,我的代码假定CSV仅由1行组成,并且所有数据都填充到$ header。
As the result, the new input CSV is having ^M ( \r\n ) characters on it, and because of that, my code assumes that the CSV is consist of 1 line only, and all the data is populated to $header.
我已将读取模式更改为 rt,因为php.net建议以t模式打开文本,但是问题仍然存在。似乎rt仅适用于Windows将\n转换为\rn
。
I have changed the read mode to "rt" since the php.net advises to open text in t mode, but the issue is still exist. It seems that rt is only works for Windows to convert \n to \rn .
从PHP.NET :Windows提供了一个文本模式转换标记('t'),该标记将透明地显示在处理文件时将\n转换为\r\n。相反,您也可以使用'b'强制使用二进制模式,该模式不会转换您的数据。要使用这些标志,请将'b'或't'指定为mode参数的最后一个字符。
From PHP.NET : Windows offers a text-mode translation flag ('t') which will transparently translate \n to \r\n when working with the file. In contrast, you can also use 'b' to force binary mode, which will not translate your data. To use these flags, specify either 'b' or 't' as the last character of the mode parameter.
有什么办法吗?最好只通过更改PHP代码来接受两种换行符(Microsoft和UNIX)?我知道有 dos2unix (ubuntu中的fromdos)命令,但是最新的Ubuntu默认情况下没有此命令,我想避免安装其他实用程序。
Is there any way to accept both kind of newline ( Microsoft and UNIX ) preferably by changing the PHP code only? I understand there is dos2unix (fromdos in ubuntu) command but latest Ubuntu does not have this by default and I want to refrain from installing other utility.
下面是我当前的源代码:
Below is my current source code :
$row = 1;
if (($handle = fopen($file, "r")) !== FALSE)
{
while (($data = fgetcsv($handle)) !== FALSE)
{
$num = count($data);
if($row == 1)
{
$header = $data;
}else
{
$rows[$row-1] = $data;
}
$row ;
}
fclose($handle);
}
正确答案
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcfhacc
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20 -
希伯来语的空格句子标记化错误
it1352 06-22