检查csv文件是否为UTF-8和PHP


Check if csv file is in UTF-8 with PHP

有没有一种方法可以在没有BOM编码的情况下检查CSV文件的UTF-8?我想检查整个文件,而不是一个字符串。

我会尝试用一个特殊字符设置第一行,然后读取字符串并检查它是否与脚本中硬编码的相同字符串匹配。但我不知道这是否是个好主意。

谷歌只给我看了这个。但上一篇文章中的链接不可用。

if (mb_check_encoding(file_get_contents($file), 'UTF-8')) {
    // yup, all UTF-8
}

如果文件很大,并且您不想一次将其全部存储在内存中,那么您也可以使用fgets逐行遍历它。不确定你问题的第二部分是什么意思。

我建议使用这个函数(来自symfony工具包):

<?php
  /**
   * Checks if a string is an utf8.
   *
   * Yi Stone Li<yili@yahoo-inc.com>
   * Copyright (c) 2007 Yahoo! Inc. All rights reserved.
   * Licensed under the BSD open source license
   *
   * @param string
   *
   * @return bool true if $string is valid UTF-8 and false otherwise.
   */
  public static function isUTF8($string)
  {
    for ($idx = 0, $strlen = strlen($string); $idx < $strlen; $idx++)
    {
      $byte = ord($string[$idx]);
      if ($byte & 0x80)
      {
        if (($byte & 0xE0) == 0xC0)
        {
          // 2 byte char
          $bytes_remaining = 1;
        }
        else if (($byte & 0xF0) == 0xE0)
        {
          // 3 byte char
          $bytes_remaining = 2;
        }
        else if (($byte & 0xF8) == 0xF0)
        {
          // 4 byte char
          $bytes_remaining = 3;
        }
        else
        {
          return false;
        }
        if ($idx + $bytes_remaining >= $strlen)
        {
          return false;
        }
        while ($bytes_remaining--)
        {
          if ((ord($string[++$idx]) & 0xC0) != 0x80)
          {
            return false;
          }
        }
      }
    }
    return true;
  }

但是当它检查字符串的所有字符时,我不建议在大文件中使用它。只需检查前10行,即

<?php
$handle = fopen("mycsv.csv", "r");
$check_string = "";
$line = 1;
if ($handle) {
    while ((($buffer = fgets($handle, 4096)) !== false) && $line < 11) {
        $check_string .= $buffer;
        $line++;
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail'n";
    }
    fclose($handle);
    var_dump( self::isUTF8($check_string) );
}