php function file_get_contents and first line of U

2019-08-27 22:49发布

I have the following code:

$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);

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.

The result of running the script is as follows:

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

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

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

3条回答
爷、活的狠高调
2楼-- · 2019-08-27 23:14

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)

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

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

EDIT : Partial Solution

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);
查看更多
Fickle 薄情
3楼-- · 2019-08-27 23:24

Please try below updated code:

$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'; }
查看更多
聊天终结者
4楼-- · 2019-08-27 23:28

(Try doing) -- wrong solution. see below

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

and there is one function file() for such cases:

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

I was WRONG!

var_dump gives us an answer:

string(2) "1
"

there is new line character in the string.

try doing:

$word = trim($line,"\r\n ");
查看更多
登录 后发表回答