PHP - echo和fgets奇怪的字符

时间:2017-07-18 18:00:42

标签: php fgets

我正在尝试使用PHP fgets在我的网站上显示文本文件的内容,但当我echo这些行与其他内容(<br>,{{ 1}},...)我得到了很奇怪的人物。

这是我的代码:

\n

以下是<?php header('Content-Type: text/plain;charset=utf-8'); $handle = @fopen("test.txt", "r"); if ($handle) { while (($buffer = fgets($handle, 4096)) !== false) { echo $buffer."<br>"; } if (!feof($handle)) { echo "Error: unexpected fgets() fail\n"; } fclose($handle); } ?> 的内容:

test.txt

这就是我得到的:

  

结果1 2 3 4 5 ... (6 - 18) 19 20

enter image description here

如果我使用<br>代替\n,我甚至不会使用中文字符:

  

结果<br>

enter image description here

我认为问题来自\n,因为当我只打印一行(没有循环)时,我会遇到同样的问题,但是如果fgets()替换$buffer({{ 1}})我得到了预期的结果。

修改

根据建议,我修改了代码以在php文件的开头添加"1",并修改了输出。

2 个答案:

答案 0 :(得分:0)

  

工作演示: http://phpfiddle.org/main/code/xrsk-a0uv

     

文字档案:: http://m.uploadedit.com/ba3s/1500405331493.txt

     

问题:在创建文本文件时,选择编码格式为UTF-16. !! UTF-8 by default for nodepad,nodepad++,sublime etc.. !!

<?php

header('Content-Type: text/plain;charset=utf-8');

$handle = @fopen("http://m.uploadedit.com/ba3s/1500405331493.txt", "r");
if ($handle) {
    while (($buffer = fgets($handle, 4096)) !== false) {
        echo $buffer."</br>";
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}

?>
  

注意:charset-utf-8

添加标头

header('Content-Type: text/plain;charset=utf-8');

  

OUTPUT使用"\n"

enter image description here

  

OUTPUT使用"</br>"

enter image description here

答案 1 :(得分:0)

我发现问题必须在文本文件中的某个位置:我创建了一个新问题,问题就消失了。

我不知道该文件的原始加密,因为朋友给了我。

如果我确切知道发生了什么,我会更新这个答案。

修改

我通过TextEdit制作了一份副本,保存时默认的编码格式是UTF-16,我想这就是问题所在。