dongzai3917 2017-05-02 17:02
浏览 167
已采纳

PHP逐行读取txt文件

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.

  • 写回答

1条回答 默认 最新

  • dongmu1390 2017-05-02 17:24
    关注

    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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办