if (mb_check_encoding(file_get_contents($file), 'UTF-8')) {
// yup, all UTF-8
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
但是当它检查字符串的所有字符时,我不建议在大文件上使用它。只需检查前 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) );
}
Run Code Online (Sandbox Code Playgroud)