oneonetwo
oneonetwo

Reputation: 97

PHP parse on tabs and line breaks

I'm trying to parse individual values in a tab seperated file with line breaks like so:

00601   166659789   799296  64.348  0.309   -66.749961  18.180555
00602   79288158    4446273 30.613  1.717   -67.17613   18.362268

I'm parsing it right now using:

$delimiter = "\t";
$splitcontents = explode($delimiter, $contentsOfFile);
foreach ( $splitcontents as $value )
{
   echo $value;
}

This works, however, when a new line occurs, the last value from the previous line and the first value of the new line are combined. So when the for loop reaches the end of the first line, the last value is actually "18.180555 00602".

How can I parse out values based on line breaks as well as tabs?

Upvotes: 1

Views: 10698

Answers (2)

MetalFrog
MetalFrog

Reputation: 10523

Looks like you're just trying to parse a tab-delimited file. Use fgetcsv and assign the delimiter as a tab.

https://www.php.net/manual/en/function.fgetcsv.php

Upvotes: 8

preinheimer
preinheimer

Reputation: 3722

Explode based on the newline first, then explode each line with the tab.

$delimiter = "\n";
$splitcontents = explode($delimiter, $contentsOfFile);
foreach ( $splitcontents as $line )
{
    $bits = explode("\t", $line);
    var_dump($bits);
}

Upvotes: 4

Related Questions