【问题标题】:php function file_get_contents and first line of UTF-8 encoded textphp 函数 file_get_contents 和 UTF-8 编码文本的第一行
【发布时间】:2013-01-07 19:12:25
【问题描述】:

我有以下代码:

$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 编码的文本或页面时没有任何问题。 更改为“file”而不是“file_get_contents”并不能解决问题。 任何建议将不胜感激。 p.s. PHP 版本 5.3.1

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

【问题讨论】:

  • 尝试 $file_array = explode("\n\r", $file);或者请分享那个文本文件。

标签: php utf-8 file-get-contents


【解决方案1】:

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

string '1' (length=4)

这就是“第一行”没有回显的原因,因为 if 条件不成立。

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

编辑:部分解决方案

您可以在第一个 if 条件之前添加此行,以按照@Tino Didriksen 的描述处理此行为以获得所需的输出。

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

【讨论】:

  • 是的,问题几乎可以肯定是该文件具有 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 解码给那些角色。
【解决方案2】:

(尝试做)——错误的解决方案。见下文

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

对于这种情况,有一个函数file()

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

我错了!

var_dump 给了我们答案:

string(2) "1
"

字符串中有换行符。

尝试做:

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

【讨论】:

    【解决方案3】:

    请尝试以下更新的代码:

    $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'; }
    

    【讨论】:

      猜你喜欢
      • 2014-03-18
      • 1970-01-01
      • 1970-01-01
      • 2012-08-02
      • 1970-01-01
      • 1970-01-01
      • 2011-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多