gpt4 book ai didi

php - 如何在php中将文件转换为UTF-8?

转载 作者:可可西里 更新时间:2023-11-01 12:53:59 34 4
gpt4 key购买 nike

我可以将文件转换为 UTF-8 格式吗?

如果我在提交后可以访问该文件

$_FILES['file']['tmp_name']

注意:用户可以上传任何字符集的 CSV 文件,我通常会遇到未知的 8 位字符集。

我试试

$row = array();
$datas = file($_FILES['file']['tmp_name']);
foreach($datas as $data) {
$data = mb_convert_encoding($data, 'UTF-8');
$row[] = explode(',', $data);
}

但问题是,这段代码删除了单引号等特殊字符。

我的第一个问题是 htmlspecialchars remove the value inside the array?

我放它是为了获得更多信息。感谢那些能提供帮助的人!

最佳答案

在将其转换为 utf-8 之前,您需要知道它是什么字符集。如果你无法弄清楚,你就不能以任何理智的方式将它转换为 utf8..然而,如果无法确定编码,将其转换为 utf-8 的疯狂方法,就是简单地去除任何在 utf-8 中不合法的字节,你也许可以将其用作后备...

警告,未经测试的代码(我突然很着急),但可能看起来像这样:

foreach ( $datas as $data ) {
$encoding = guess_encoding ( $data );
if (empty ( $encoding )) {
// encoding cannot be determined...
// as a fallback, we simply strip any bytes that isnt valid utf-8...
// obviously this isn't a reliable conversion scheme.
// also this could probably be improved
$data = iconv ( "ASCII", "UTF-8//TRANSLIT//IGNORE", $text );
} else {
$data = mb_convert_encoding ( $data, 'UTF-8', $encoding );
}
$row [] = explode ( ',', $data );
}
function guess_encoding(string $str): string {
$blacklist = array (
'pass',
'auto',
'wchar',
'byte2be',
'byte2le',
'byte4be',
'byte4le',
'BASE64',
'UUENCODE',
'HTML-ENTITIES',
'7bit',
'8bit'
);
$encodings = array_flip ( mb_list_encodings () );
foreach ( $blacklist as $tmp ) {
unset ( $encodings [$tmp] );
}
$encodings = array_keys ( $encodings );
$detected = mb_detect_encoding ( $str, $encodings, true );
return ( string ) $detected;
}

关于php - 如何在php中将文件转换为UTF-8?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46842606/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com