PHP – while loop (!feof()) isn’t outputting/showing everything

Thats because your test for EOF is before you output your last read

Try this with the test for EOF as part of the reading process

<?php
$line_count = 0;

$handle = fopen("item_sets.txt", "r");

if ($handle) {

    while (($buffer = fgets($handle, 4096)) !== false) {
        $trimmed = trim($buffer);
        echo $trimmed;
        $line_count++;
    }
} else {
    echo 'Unexpected error opening file';
}
fclose($handle);

echo PHP_EOL.PHP_EOL.PHP_EOL.'Lines read from file=" . $line_count;
?>

Also I removed the @ infront of the fopen its bad practice to ignore errors, and much better practice to look for them and deal with them.

I copied your data into a file called tst.txt and ran this exact code

<?php
$handle = fopen("tst.txt', 'r');

if ($handle) {

    while (($buffer = fgets($handle, 4096)) !== false) {
        $trimmed = trim($buffer);
        echo $trimmed;
    }
} else {
    echo 'Unexpected error opening file';
}
fclose($handle);

And it generated this output ( just a small portion shown here )

"item_sets"{"set_community_3"{"name"            "#CSGO_set_community_3""set_description"                "#CSGO_set_community_3_desc""is_collection"

And the last output is

[aa_fade_revolver]weapon_revolver"          "1"

Which is the last entry in the data file

Leave a Comment