我编写了一个类,然后扩展SplFileObject以打开CSV并具有关联数组。它是有效的,但如果csv文件使用CR换行,则无效。
我知道你可以这样转换字符串换行:
$string = str_replace($this::CRLF, $string::LF, $file);
$string = str_replace($this::CR, $string::LF, $file);
但我想知道如何在构造函数中转换换行符。
我如何创建我的文件:
$file = new CSVFile(__DIR__ . '/../../Resources/data/myfile.csv');
CSVFile.php 类
use 'SplFileObject;
class CSVFile extends SplFileObject
{
private $keys;
public function __construct($file)
{
parent::__construct($file);
$this->setFlags(SplFileObject::READ_CSV);
}
public function rewind()
{
parent::rewind();
$this->keys = parent::current();
parent::next();
}
public function current()
{
return array_combine($this->keys, parent::current());
}
public function getKeys()
{
return $this->keys;
}
}
不太确定你想做什么,但你尝试过吗?ini_set('auto_detect_line_endings',true);
我能想到的唯一方法(希望php提供一些我不知道的支持)是读取文件,替换换行符,写入临时文件,然后打开临时文件。