Search code examples
phpcsvtabsfgetcsv

PHP Parsing a .dat file


I have a .dat file that is essentially ; delimited file and I'm trying to convert it to a tab delimited .txt. The problem that I am not sure about is that each row of the new file will be a combination of 3 of the original file's rows, each original row has a different quantity of data. The first column just identifies each row in a grouping. What would be the best way to do this?

Sample original data:

01;zxc;asd;qwe;uio;jkl;asd;123;456
02;lkj;oiu;oji
03;fjifao;vbofekjf;fjieofk;aoijf;voien3984
01;lkj;oiu;fji;eoj;vnk;fji;098;321
02;fji;oje;jvi
03;jie;voi;djv;eojf;38723

End output:

zxc   asd   qwe   uio   jkl   asd   123   456   lkj   oiu   oji   fjifao   vbofekjf   fjieofk   aoijf   voien3984
lkj   oiu   fji   eoj   vnk   fji   098   321   fji   oje   jvi   jie   voi   djv   eojf   38723

Any ideas?


Solution

  • Here's how I'd do it:

    $lines = file($data);
    $rows = array();
    $row_pivot = -1;
    foreach ($lines as $line) {
    
        // Split line by ;
        $data = explode(';', trim($line));
    
        // Get the first element
        $r_id = array_shift($data);
        if ($r_id == '01') {
            // When 01 is the first element, start a new row
            // You can dump the previous row here as well if you aim for speed
            $row_pivot++;
            $rows[$row_pivot] = array();
        }
    
        // Add data to row
        $rows[$row_pivot] = array_merge($rows[$row_pivot], $data);
    }
    
    // Print rows
    foreach ($rows as $r) {
        echo implode("\t", $r)."\n";
    }