The problem might be your use of !feof
: you're checking if you haven't already reached the end of the file, and that's fine, but you're not checking the return value of fgets
. The last line in a file often is just a new-line character, so on your last iteration, it's not unlikely that $line
ends up being an empty string.
You're also re-assigning $array
, each time replacing the previous values you assigned to it. If the loop you posted is situated outside of the while
loop, it's not unlikely that what you're doing is actually this:
$line = '';//as explained, $line might be an empty string
$array = str_getcsv($line, "\t");//which is $array = array();
If you then attempt to lop over this empty array, you're not going to echo anything:
foreach (array() as $a)
echo $a;//there are no values to echo...
Your best bet is to construct a 2D array:
$array = array();
while(...)
$array[] = $lineAsArray;
This is pseudo-code, because the while-loop you have can be simplified a lot:
Why not use the fgetcsv
function with a custom delimiter?
$fh = fopen('myFile.txt', 'r');
if (!$fh)
exit(1);//handle error
while ($line = fgetcsv($fh, 2048, "\t"))
{//line is an array of CSV values now
echo implode('<br>', $line), '<br>';//echo all values
}
That's all there is too it. Instead of implode
you can loop over line, but seeing as you're just echoing all values, followed by <br>
, I figured using implode
just made more sense.
I don't know for sure what your file looks like, but the longest line might be longer than 2048 bytes, you can take advantage of the fact that PHP can handle a 0
length argument. If the length is zero, the line will be read until an EOL, or EOF is encountered:
while ($line = fgetcsv($fh, 0, "\t"))
That'll work just fine...
Bottom line:
I think that you're looking for something along the lines of:
$fh = fopne('myFile.txt', 'r');
if (!$fh)
exit(1);//handle error
$array = array();
$alternative = array();
while($line = fgetcsv($fh, 0, "\t"))
{
$array[] = $line;
//or if you simply want to echo:
$alternative[] = implode('<br>', $line);
}
//the short alternative
echo implode('<br>', $alternative);
//the long way:
foreach ($array as $line)
{
echo implode('<br>',$line), '<br>';
}
Both amount to the ssame thing