PHP - while loop (!feof()) isn't outputting/showing everything

♀尐吖头ヾ 提交于 2019-11-26 03:45:58

问题


I am trying to read (and echo) everything of a .txt-File.

This is my code:

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

while (!feof($handle))
{
    $buffer = fgets($handle, 4096);
    $trimmed = trim($buffer);
    echo $trimmed;
}

This is my \"item_sets.txt\": http://pastebin.com/sxapZGuW

But it doesn\'t echo everything (and changing how much it shows depending on if and how many characters i echo after it). var_dump() shows me that the last string is never finished printing out. That looks like this:

\" string(45) \"\"[cu_well_tra. But if I put an

echo \"whateverthisisjustarandomstringwithseveralcharacters\";,

my last output lines look like this:

\" string(45) \"\"[cu_well_traveled_ak47]weapon_ak47\" \"1\" \" string(5) \"} \"

Basically my code isn\'t printing/echoing all of what it should or at least not showing it.

Thanks in advance :)


回答1:


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



来源:https://stackoverflow.com/questions/34425804/php-while-loop-feof-isnt-outputting-showing-everything

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