Nir Tzezana Nir Tzezana - 1 month ago 7
PHP Question

Insert into array by spaces

I have this TXT file, which each line I would to insert into array, like this:


Array ( [0] => [1] => 8100 [2] => 623 [3] => 09:04 [4] => AM [5] => 00:26 [6] => L [7] => S-ED [8] => 768 [9] => #4506856439 [10] => 00:01 [11] => )


CO USER TIME DURATION TYPE ACCOUNT_CODE CALLED_NUM RING_TIME
8100 623 09:04 AM 00:26 L S-E 250821613987
8021 8816 09:06 AM 00:20 I S-E D 768 #4506856439 00:01
8020 09:06 AM I N D 603 #45424044499 00:30
8011 09:07 AM 00:11 I S-E D 727 #7546355292 00:02
" 8817 00:11
" 00:02 H
8100 623 09:07 AM 00:01 L S-E 5542204034
8007 8818 09:08 AM 00:13 I S-E D 618 #45269021726 00:01
8013 8811 09:09 AM 00:01 I S-E D 770 #436217227 00:01
8014 09:10 AM 00:16 I S-E D 652 #4523859922 00:01


I'd like to insert it into an array with all parameters, even if empty,

but I can't get it work.

I tried this:

$fh = fopen('captures/131210.txt','r');
while ($line = fgets($fh)) {
$tempexp = preg_split('/\s+/', $line);
print_r($tempexp);
echo "<br />";
}
fclose($fh)


But it gives out weird outputs for some values, like this:


Array ( [0] => [1] => " [2] => 8812 [3] => 00:16 [4] => )


Help would be much appreciated!

Answer

If the layout of your text file is purely based on spaces you can used the exact columns to extract the data. Since the columns are not of equal width you cannot simply write it in one loop.

Use the substr function to get part of the line (first number is index, second number is length to read)

$fh = fopen('captures/131210.txt','r');
 while ($line = fgets($fh)) {
  $co = substr($line, 0, 7);
  $user = substr($line, 7, 6);
  ... etc ...
  echo "<br />";
 }
fclose($fh)

You might need to parse the separate parts further down dependent on the content and what you want to do with it - parse as integer, date, time etc.

Comments