开发者

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;eo开发者_开发问答jf;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?


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";
}


I would personally explode the data then foreach row in the resulting array, then again explode each line at your delimiter ';' and then format an output that is tab delimited.

<?php

$data = 'LOADED FILE DATA';
$lines = preg_split( '/\r\n|\r|\n/', $data);
$out = '';

foreach($lines as $line){
    $parts = explode(';',$line);
    foreach($parts as $part){
        $out .= $part.'\t';
    }
    $out .= '\n';
}

echo $out;

?>

code untested.


Should be something like this

$lines = file($filename);
$lineCount = count($lines);
$output = '';
for ($i = 0; $i < $lineCount - 2; $i += 3) {
  $newLines = array();
  for ($j = $i; $j < $i + 3; $j++) {
    list($_, $rest) = explode(';', isset($lines[$j]) ? $lines[$j] : '');
    $newLines = array_merge($newLines, $rest);
  }

  $output .= implode("\t", $newLines) . "\n";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜