将制表符分隔的文本文件转换为csv php时跳过列

时间:2017-07-18 13:08:51

标签: php csv tab-delimited-text

我正在尝试将制表符分隔文件转换为csv。问题是它是一个巨大的文件。 100000多条记录。我只想要该文件中的特定列。该文件不是由我生成的,而是由亚马逊生成的,因此我无法真正控制格式。

我制作的代码很好。但我需要忽略/删除一些列,或者我只需要几列。如何在不影响从txt到csv的转换性能的情况下执行此操作。

$file = fopen($file_name.'.txt','w+');
fwrite($file,$report);
fclose($file);

$handle = fopen($file_name.".txt", "r");
$lines = [];
$row_count=0;
$array_count = 0;
$uid = array($user_id);
if (($handle = fopen($file_name.".txt", "r")) !== FALSE) 
{
    while (($data = fgetcsv($handle, 100000, "\t")) !== FALSE) 
    {
        if($row_count>0)
        {
            $lines[] = str_replace(",","<c>",$data);
            array_push($lines[$array_count],$user_id);
            $array_count++;
        }
        $row_count++;
    }
    fclose($handle);
}
$fp = fopen($file_name.'.csv', 'w');
foreach ($lines as $line) 
{
    fputcsv($fp, $line);
}

fclose($fp);

我正在使用unset删除任何列。但有更好的方法吗?对于多列。

2 个答案:

答案 0 :(得分:0)

我会通过检查键来做到这一点。例如:

// columns keys you don't wanna skip
$keys = array(0, 1, 3, 4, 7, 9);
$lines = file($file_name);
$result_lines = array();
foreach ($lines as $line) {
    $tmp = array();
    $tabs = explode("\t", $line);  
    foreach($tabs as $key => $value){
        if(in_array($key, $keys)){
            $tmp[] = $value;
        }
    }
    $result_lines[] = implode(",", $tmp);
}
$finalString = implode("\n", $result_lines);
// Then write string to file

希望它有所帮助。 干杯, 西尼沙

答案 1 :(得分:0)

以最简单的形式,即不必担心从输出中删除列,这将执行简单的读取行和写入行,因此无需维护任何内存饥饿的数组。

$file_name = 'tst';
if ( ($f_in = fopen($file_name.".txt", "r")) === FALSE) {
    echo 'Cannot find inpout file';
    exit;
}
if ( ($f_out = fopen($file_name.'.csv', 'w')) === FALSE ) {
    echo 'Cannot open output file';
    exit;
}

while ($data = fgetcsv($f_in, 8000, "\t")) {
    fputcsv($f_out, $data, ',', '"');
}

fclose($f_in);
fclose($f_out);

这是删除不需要的列的一种方法

$file_name = 'tst';
if ( ($f_in = fopen("tst.txt", "r")) === FALSE) {
    echo 'Cannot find inpout file';
    exit;
}
if ( ($f_out = fopen($file_name.'.csv', 'w')) === FALSE ) {
    echo 'Cannot open output file';
    exit;
}

$unwanted = [26,27]; //index of unwanted columns

while ($data = fgetcsv($f_in, 8000, "\t")) {
    // remove unwanted columns
    foreach($unwanted as $i) {
        unset($data[$i]);
    }
    fputcsv($f_out, $data, ',', '"');
}

fclose($f_in);
fclose($f_out);