php函数文件获取内容和UTF-8编码文本的第一行

php函数文件获取内容和UTF-8编码文本的第一行,php,utf-8,file-get-contents,Php,Utf 8,File Get Contents,我有以下代码: $array_test = array(); $file = file_get_contents ('./test.txt'); $file_array = explode("\n", $file); foreach ($file_array as $line) { $word = trim($line); $array_test[] = $word; } echo $array_test[0]; if ($array_test[0] == "1")

我有以下代码:

$array_test = array();

$file = file_get_contents ('./test.txt');

$file_array = explode("\n", $file);

foreach ($file_array as $line) {

    $word = trim($line);
    $array_test[] = $word;
}

echo $array_test[0];

if ($array_test[0] == "1") { echo 'first line'; }

echo $array_test[1];

if ($array_test[1] == "2") { echo 'second line'; }

print_r ($array_test);
test.txt文件以UTF-8编码。它有5行。每一行我都有一个数字:1-第一行,2-第二行,等等

运行脚本的结果如下所示:

1
2
second line
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
正如你看到的,第一行有问题。看起来它被正确地添加到了数组中,但不知何故它的值与“1”不同。其他线路没有问题,只有第一条线路。 这个问题可以通过跳过第一行并开始向数组中添加第二行的值来解决,但我只是想知道为什么它不能像我写的那样工作? 通常我在显示或读取UTF8编码的文本或页面时没有任何问题。 将“文件获取内容”改为“文件”并不能解决问题。 如有任何建议,将不胜感激。 p、 美国PHP版本5.3.1

更新:问题是UTF-8 BOM。请参阅下面的解决方案。谢谢大家的帮助

(尝试执行)--错误的解决方案。见下文

if($array_test[0] === "1") echo "first line";
这种情况下有一个功能:

$file = file_get_contents ('./test.txt');
$file_array = explode("\n", $file);
我错了

var_dump给了我们一个答案:

string(2) "1
"
字符串中有新行字符

试着做:

$word = trim($line,"\r\n ");

请尝试以下更新的代码:

$array_test = array();

$file = file_get_contents ('./test.txt');

$file_array = explode("\n", $file);

foreach ($file_array as $line) {

    $word = trim($line);
    $array_test[] = $word;
}

echo $array_test[0];

if ($array_test[0][0] == "1") { echo 'first line'; }

echo $array_test[1];

if ($array_test[1][0] == "2") { echo 'second line'; }

主要问题是这个,但我还不能解决它。在var_dump($array_test[0])上,我得到以下输出:

string '1' (length=4)
这就是“第一行”在if条件未变为真时不回显的原因

此外,如果您可以共享
test.txt
文件,则很容易发现问题

编辑:部分解决方案

您可以在first if条件之前添加这一行来处理@Tino Didriksen所描述的行为,以获得所需的输出

$array_test[0] = substr_replace($array_test[0],'',0,3);

try$file\u array=explode(“\n\r”,$file);或者请共享该文本文件。是的,问题几乎肯定是该文件有UTF-8 BOM。如果文件的前3个字节正好是0xEF 0xBB 0xBF(在纯文本编辑器中看起来像“”),则应该丢弃它们。谢谢!它是UTF-8 BOM。最后的解决方案-我添加了以下行:if(substr($file,0,3)==pack(“CCC”,0xef,0xbb,0xbf)){$file=substr($file,3);}并且它工作得很好。@TinoDidriksen,原理是错误的,并不是因为您使用的是纯文本编辑器,而是因为您使用的是Windows-1252进行解码,而Windows-1252中的UTF-8 bom将解码为这些字符。