Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

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

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 :)

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...