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!