我有一个定期更新的CSV文件,需要使用制表符分隔该文件,才能将其导入链中更深的一些工具。
我的问题是:如何使用PHP(7.3)将CSV转换为TAB分隔的TXT文件?
注意:简单地将“,”替换为“ / t”将不起作用,因为引号中包含逗号。我有大量的列标题(超过50个),并且这些列标题有时可能会更改,因此我不想在f * scv函数中命名它们(我可以从手册页中看到)。
我当前的代码如下所示,但是输出空白。
$handle = fopen("//catalyst-sabre-bucket//the_reporting//test//mit.csv", "r");
$lines = [];
if (($handle = fopen("//my-path//the_reporting//test//mit.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$lines[] = $data;
}
fclose($handle);
}
$fp = fopen('//my-path//ocb_reporting//test//mit-tab.txt', 'w');
foreach ($lines as $line) {
fputcsv($fp, $line, "\t");
}
fclose($fp);
示例输入:
Field,Place,Thing,Object,Comment,Measure
1,left,Apple,Bowl,This field contains text,Imperial
a,right,orange,House,"But, this one has commas & characters",Metric
blue,Far,car,A really large blue canary,"This, one, is, a user comment",Turtles
示例输出:
Field Place Thing Object Comment Measure
1 left Apple Bowl This field contains text Imperial
a right orange House "But, this one has commas & characters" Metric
blue Far car A really large blue canary "This, one, is, a user comment" Turtles
在提供的样本数据上,以下内容在本地测试时似乎工作正常。替换根据正则表达式完成
<?php
$output=[];
$file='//catalyst-sabre-bucket//the_reporting//test//mit.csv';
$lines=file( $file ); #read directly into an array
$pttn='/"[^"]*"(*SKIP)(*FAIL)|,/i'; # find commas not between quotes & replace with TAB
foreach( $lines as $line ){
$output[]=preg_replace( $pttn, chr(9), $line );
}
#write output to text file
$file='//my-path//ocb_reporting//test//mit-tab.txt';
file_put_content( $file, implode( '', $output ) );
?>
以上的输出已成功地以文本形式写入文本文件:
Field Place Thing Object Comment Measure
1 left Apple Bowl This field contains text Imperial
a right orange House "But, this one has commas & characters" Metric
blue Far car A really large blue canary "This, one, is, a user comment" Turtles