固定寬度文本文件(如銀行對賬單、主機導出數據)需轉為 CSV 導入數據庫或分析。本文提供一個繼承 SplFileObject 的 Fixed2CSV 類,支援自定義字段位置/寬度、分隔符、行尾符,並可選擇性輸出指定字段,內存效率高。
class Fixed2CSV extends SplFileObject {
private $fields = []; // [startPos => width, ...]
private $separator = ',';
private $eol = "\n";
public function __set($name, $value) {
if (in_array($name, ['fields','separator','eol'])) $this->$name = $value;
else throw new Exception("Unknown property: $name");
}
public function __get($name) {
if (in_array($name, ['fields','separator','eol'])) return $this->$name;
throw new Exception("Unknown property: $name");
}
// 核心:重寫 current() 將固定寬度行轉為 CSV
public function current() {
$line = parent::current();
if ($line === false) return false;
$csv = '';
$fieldsIter = new CachingIterator(new ArrayIterator($this->fields));
foreach ($fieldsIter as $start => $width) {
$csv .= trim(substr($line, $start, $width));
$csv .= $fieldsIter->hasNext() ? $this->separator : $this->eol;
}
return $csv;
}
}
try {
// 文件每行固定寬度:0-9(10字符) | 10-24(15字符) | 25-44(20字符) | 45-69(25字符)
$file = new Fixed2CSV('data/fixed_width.txt');
$file->fields = [0=>10, 10=>15, 25=>20, 45=>25];
$file->separator = ',';
$file->eol = "\n";
echo "完整輸出:\n";
foreach ($file as $line) echo $line;
// 僅導出第 1、3 字段
$file2 = new Fixed2CSV('data/fixed_width.txt');
$file2->fields = [0=>10, 25=>20];
echo "\n僅導出字段 1 和 3:\n";
foreach ($file2 as $line) echo $line;
} catch (Exception $e) {
echo '錯誤:' . $e->getMessage();
}
Iterator、SeekableIterator、Countable,支援 foreach、seek()、count(),逐行讀取內存常駐極低。$fields 陣列鍵為起始位置(0 基),值為寬度,可任意組合、跳過字段。\n/\r\n。setEncoding($from, $to) 支援字符集轉換(如 GBK→UTF-8)。skipLines($n) 跳過文件頭說明行。validateLine($line) 鉤子,過濾不符合格式的髒數據。利用 SPL 迭代器特性,Fixed2CSV 以極少代碼實現了高效、靈活的固定寬度轉 CSV,是數據遷移與集成項目中的得力工具。