简体   繁体   中英

PHP Read txt file line by line

I have this PHP code:

$myfile = fopen("index.txt", "r") or die("Unable to open file!");

//rewind($myfile);
fseek($myfile, 0);

while(!feof($myfile)) {
    $line=fgets($myfile);
    echo $line;
    echo strpos($line,":");
    echo "<br />";
}

fclose($myfile);

index.txt contains the following data:

:a
1:b
2:c

result:

:a 3
1:b 1
2:c1

I'm having problem with the function strops , it doesn't give the accurate position number.

As you can see in the result, I get the number 3 while it should be 0 and there is a white space added between the letter a & the number 3 (and between the letter b & the number 1 ). Why is that?

As you can see above, I tried to set the file pointer position to 0, but didn't work.

Thanks.

Your index.txt has UTF-8 encoding. But commonly used is "UTF-8 without BOM". Difference between them is that the 1st one has three bytes at the beginning of the file (ef bb bf). You should change the encoding of your index.txt file.

The other universal solution (no matter has file the BOM or not) is to check for the BOM in your string (just for the 1st line of the file). Below is the function for checking and removing BOM bytes. Just apply it to your $line: $line=removeBOM(fgets($myfile));

function removeBOM($text) {
    if(substr($text, 0, 3) == pack('CCC', 0xef, 0xbb, 0xbf)) {
        $text= substr($text, 3);
    }
    return $text;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM