PHP - echo 和 fgets 奇怪的字符

PHP - echo and fgets weird characters

我正在尝试使用 PHP 的 fgets 在我的网站上显示文本文件的内容,但是当我 echo 将这些行与其他内容结合使用时 ( <br>, \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

这是我得到的:

Result with <br>

如果我用\n而不是<br>,我连汉字都看不懂:

Result with \n

我认为问题来自 fgets(),因为当我只打印一行(没有循环)时,我遇到了同样的问题,但是如果将 $buffer 替换为 "1"echo "1"."<br>";) 我得到了预期的结果。

编辑

按照建议,我修改了代码,在 php 文件的开头添加了 header('Content-Type: text/plain;charset=utf-8');,并修改了输出。

Working DEMO: http://phpfiddle.org/main/code/xrsk-a0uv

Text File:: http://m.uploadedit.com/ba3s/1500405331493.txt

Problem: at the Time of create text file it's select the encoding format is 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);
}

?>

NOTE: Add header for charset-utf-8

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

OUTPUT Using With "\n"

OUTPUT Using With "</br>"

我发现问题一定出在文本文件中:我创建了一个新文件,问题消失了。

我不知道文件的原始加密方式,因为是朋友给我的。

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

编辑

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