php函数file_get_contents和UTF-8编码文本的第一行 [英] php function file_get_contents and first line of UTF-8 encoded text

查看:220
本文介绍了php函数file_get_contents和UTF-8编码文本的第一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

$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-第二行,等等.

The test.txt is file encoded in UTF-8. It has 5 lines. On each line I have a number: 1 - first line, 2 - second line, etc.

运行脚本的结果如下:

1
2
second line
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

如您所见,第一行存在问题.似乎已正确将其添加到数组,但其值与"1"有所不同.其他线路没有任何问题,只有第一条. 可以通过跳过第一行并开始将第二行中的值添加到数组中来解决该问题,但是我只是想知道为什么它不能按照我的编写方式工作? 通常,我在显示或阅读UTF8编码的文本或页面时没有任何问题. 更改为文件"而不是"file_get_contents"并不能解决问题. 任何建议将不胜感激. p.s. PHP版本5.3.1

As you can see there's a problem with the first line. It seems that it was added to the array correctly, but somehow its value differs from "1". There's no problems with the other lines, just the first one. The problem can be fixed by skipping the first line and starting to add to the array the values from the second line, but I'm just wondering why it doesn't work the way I wrote it? Usually I don't have any problems with displaying or reading UTF8 encoded texts or pages. Changing to "file" instead of "file_get_contents" doesn't solve the problem. Any suggestion would be very appreciated. p.s. PHP Version 5.3.1

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

UPDATE: The problem was UTF-8 BOM. See the solution below. Thanks everybody for the help!

推荐答案

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

The main issue is this but I am not able to solve it yet. On var_dump($array_test[0]) I get the following output:

string '1' (length=4)

这是因为if条件不成立而未回显第一行"的原因.

This is the reason 'first line' is not echoed as the if condition is not getting true.

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

Also if you can share your test.txt file it will be easy to catch the problem.

部分解决方案

您可以在第一个if条件(如@Tino Didriksen所述)处理此行为之前添加此行,以获取所需的输出.

You can add this line before first if condition to handle this behaviour as described by @Tino Didriksen to get your desired output.

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

这篇关于php函数file_get_contents和UTF-8编码文本的第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆