PHP Parsing a .dat file

这一生的挚爱 提交于 2019-12-11 00:27:14

问题


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?


回答1:


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



回答2:


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.



回答3:


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


来源:https://stackoverflow.com/questions/6657191/php-parsing-a-dat-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!